package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.config.CommonPropertiesConfig;
import com.ytjj.qmyx.mall.config.SupplyApiConfig;
import com.ytjj.qmyx.mall.constants.*;
import com.ytjj.qmyx.mall.enums.*;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.dto.*;
import com.ytjj.qmyx.mall.model.request.ProductReceiveRequest;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.mall.utils.*;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersAddressMapper;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动接口实现
 *
 *
 * @version 1.0
 *
 */
@Service
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityColumnMapper activityColumnMapper;

    @Resource
    private ProductActivityMapper productActivityMapper;

    @Resource
    private ProductReviewsMapper productReviewsMapper;

    @Resource
    private ProductActivityImgMapper productActivityImgMapper;

    @Resource
    private ProductActivitySpecMapper productActivitySpecMapper;

    @Resource
    private RedisService redisService;

    private final UsersClient usersClient;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private NavMapper navMapper;

    @Resource
    private BannersMapper bannersMapper;

    @Resource
    private ProductRecordUtil productRecordUtil;

    @Resource
    private ProductDao productDao;

    @Resource
    private FakeUserUtil fakeUserUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private OrdersDao ordersDao;

    @Resource
    private UsersInfoMapper usersInfoMapper;

    @Resource
    private ProductService productService;

    @Resource
    private EvaluationProductDao evaluationProductDao;

    @Resource
    private ProductActivityDao productActivityDao;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private CouponRecordsDao couponRecordsDao;

    @Resource
    private CouponRecordsMapper couponRecordsMapper;

    @Resource
    private HotProductMapper hotProductMapper;

    @Resource
    private BankerSiteDao bankerSiteDao;

    @Resource
    private SubjectsMapper subjectsMapper;

    @Resource
    private ProductSubjectPlateMapper productSubjectPlateMapper;

    @Resource
    private UsersAddressMapper usersAddressMapper;

    @Resource
    private NewExclusiveDao newExclusiveDao;
    @Resource
    private SupplyApiConfig supplyApiConfig;

    @Resource
    private BrandMapper brandMapper;
    @Value("${app.fixPrice:60}")
    private String fixPriceParam;

    // 官网栏目 - 兑换排行
    @Value("${app.ranking:9}")
    private String CHANGE_RANKING;

    // 官网栏目 - 猜你喜欢
    @Value("${app.like:10}")
    private String GUESSYOU_LIKE;

    // 官网栏目 - 精选好物
    @Value("${app.good:8}")
    private String CHOICENESS_GOODTHING;

    @Resource(name = "mallCommonPropertiesConfig")
    private CommonPropertiesConfig commonPropertiesConfig;

    //超值兑换
    private static final Integer SUPER_CHANGE_COLUMN_ID = 8;
    //兑换排行
    private static final Integer CHANGE_SENIORITY=9;
    //猜你喜欢
    private static final Integer GET_LIKE_COLUMN_ID = 10;
    //偏远-猜你喜欢
    private static final Integer REMOTE_REGION_GET_LIKE = 144;
    //精选积分
    private static final Integer VERY_SCORE_COLUMN_ID = 26;

    public ActivityServiceImpl(UsersClient usersClient) {
        this.usersClient = usersClient;
    }

//    @Override
//    public List<ActivityColumnResponse> getSeckillColumn() {
//        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
//        activityColumnExample.createCriteria()
//                .andTypeEqualTo(ActivityTypeEnums.SECKILL.name())
//                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
//        List<ActivityColumn> seckillColumns = activityColumnMapper.selectByExample(activityColumnExample);
//
//        // 查询广告商品
////        ProductActivityExample pa = new ProductActivityExample();
////        pa.setOrderByClause("sort desc");
////        pa.createCriteria()
////                .andColumnIdEqualTo(4)
////                .andIsHideEqualTo(0)
////                .andIsAdvertEqualTo(1)
////                .andDataTypeEqualTo(TokenUtil.getDataType())
////                .andActivityTypeEqualTo(ActivityTypeEnums.SECKILL.name());
////        List<ProductActivity> advertList = productActivityMapper.selectByExample(pa);
////        List<ProductActivityResponse> advertCollect = advertList.stream()
////                .map(item -> new ProductActivityResponse(item, this.getFakeUserList()))
////                .collect(Collectors.toList());
//
//        // 查询不是广告商品
//        ProductActivityExample productActivityExample = new ProductActivityExample();
//        productActivityExample.setOrderByClause("sort desc");
//        productActivityExample.createCriteria()
//                .andColumnIdEqualTo(4)
//                .andIsHideEqualTo(0)
//                .andIsAdvertEqualTo(0)
//                .andPlatformDataIn(Arrays.asList("all","h5"))
//                .andDataTypeEqualTo(TokenUtil.getDataType())
//                .andActivityTypeEqualTo(ActivityTypeEnums.SECKILL.name())
//                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
//                        ProductActivityStatusEnums.PRESELL.getValue()));
//        List<ProductActivity> productActivities = productActivityMapper.selectByExample(productActivityExample);
//        List<ProductActivityResponse> collect = productActivities.stream()
//                .map(childItem -> new ProductActivityResponse(childItem, this.getFakeUserList()))
//                .collect(Collectors.toList());
//        Collections.shuffle(collect);
//        List<ActivityColumnResponse> list = seckillColumns.stream()
//                // 排序
//                .sorted((item1, item2) -> {
//                    LocalTime time1 = LocalTime.parse(item1.getTime(), DateTimeFormatter.ofPattern("HH:mm"));
//                    LocalTime time2 = LocalTime.parse(item1.getTime(), DateTimeFormatter.ofPattern("HH:mm"));
//                    return time1.compareTo(time2);
//                })
//                // 转换组装
//                .map(item -> {
//                    ActivityColumnResponse response = new ActivityColumnResponse();
//                    BeanUtils.copyProperties(item, response);
//                    List<ProductActivityResponse> paList = new ArrayList<>();
//                    // paList.addAll(advertCollect);
//                    paList.addAll(collect);
//                    response.setProductList(paList);
//                    return response;
//                })
//                .collect(Collectors.toList());
//
//        return this.processingTime(list);
//    }

    private List<ActivityColumnResponse> processingTime(List<ActivityColumnResponse> responses) {
        LocalTime localTime = LocalTime.now();
        for (int i = 0; i < responses.size(); i++) {
            if (i == responses.size() - 1) {
                ActivityColumnResponse item1 = responses.get(i);
                LocalTime time1 = LocalTime.parse(item1.getTime(), DateTimeFormatter.ofPattern("HH:mm"));
                if (1 == time1.compareTo(localTime)) {
                    item1.setStatus(SeckillTextEnums.TEXT3.getCode());
                    item1.setTimeText(SeckillTextEnums.TEXT3.getMsg());
                } else {
                    responses.get(i).setStatus(SeckillTextEnums.TEXT2.getCode());
                    item1.setTimeText(SeckillTextEnums.TEXT2.getMsg());
                }
                break;
            }
            ActivityColumnResponse item1 = responses.get(i);
            ActivityColumnResponse item2 = responses.get(i + 1);
            LocalTime time1 = LocalTime.parse(item1.getTime(), DateTimeFormatter.ofPattern("HH:mm"));
            LocalTime time2 = LocalTime.parse(item2.getTime(), DateTimeFormatter.ofPattern("HH:mm"));
            if (1 == localTime.compareTo(time1) && 1 == time2.compareTo(localTime)) {
                responses.get(i).setStatus(SeckillTextEnums.TEXT2.getCode());
                item1.setTimeText(SeckillTextEnums.TEXT2.getMsg());
                item2.setStatus(SeckillTextEnums.TEXT3.getCode());
                item2.setTimeText(SeckillTextEnums.TEXT3.getMsg());
            } else {
                if (-1 == localTime.compareTo(time1)) {
                    item1.setStatus(SeckillTextEnums.TEXT3.getCode());
                    item1.setTimeText(SeckillTextEnums.TEXT3.getMsg());
                } else {
                    item1.setStatus(SeckillTextEnums.TEXT1.getCode());
                    item1.setTimeText(SeckillTextEnums.TEXT1.getMsg());
                }
            }
        }
        return responses;
    }

    @Override
    public List<ProductResponse> getNewUserProductList() {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.NEW_USER.name())
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> productList = productMapper.selectByExample(productExample);
        return productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductResponse> getReturnCashProductList() {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.RETURN_CASH.name())
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<Product> productList = productMapper.selectByExample(productExample);
        return productList.stream()
                .map(item -> new ProductResponse(item, this.getFakeUserList()))
                .collect(Collectors.toList());
    }

    @Override
    public List<ActivityColumnResponse> getOldForNewColumn() {
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.setOrderByClause("sort desc");
        activityColumnExample.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> activityColumns = activityColumnMapper.selectByExample(activityColumnExample);
        return activityColumns.stream().map(item -> {
            ActivityColumnResponse response = new ActivityColumnResponse();
            ProductExample productExample = new ProductExample();
            productExample.setOrderByClause("sort desc");
            productExample.createCriteria()
                    .andColumnIdEqualTo(item.getId())
                    .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                    .andBankerColumnIdNotIn(Arrays.asList(1, 3))
                    .andDataTypeEqualTo(TokenUtil.getDataType())
                    .andIsAdvertEqualTo(0)
                    .andIsHideEqualTo(0)
                    .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                    .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                            ProductActivityStatusEnums.PRESELL.getValue()));
            List<Product> productList = Optional.ofNullable(productMapper.selectByExample(productExample)).orElse(new ArrayList<>());
            BeanUtils.copyProperties(item, response);
            response.setProductList(productList.stream()
                    .map(product -> {
                        ProductShortResponse productResponse = new ProductShortResponse(product);
                        BigDecimal originalPrice = Optional.ofNullable(productResponse.getOriginalPrice()).orElse(BigDecimal.ZERO);
                        BigDecimal price = Optional.ofNullable(productResponse.getPrice()).orElse(BigDecimal.ZERO);
                        productResponse.setSubsidy(
                                originalPrice.compareTo(price) > 0
                                        ? originalPrice.subtract(price).setScale(2, BigDecimal.ROUND_UP)
                                        : BigDecimal.ZERO);
                        return productResponse;
                    })
                    .collect(Collectors.toList()));
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public List<ProductResponse> getNewProductList() {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andActivityTypeEqualTo(ActivityTypeEnums.NEW_PRO.name())
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> productList = productMapper.selectByExample(productExample);
        return productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
    }


    @Override
    public ProductResponse getActivityProductInfoByProductId(Integer id, String type) {
        Product product = productMapper.selectByPrimaryKey(id);
        ProductResponse productResponse = new ProductResponse(product);
        return productResponse;
    }

    @Override
    public ProductResponse getActivityProductInfo(Integer id, String type, String modular) {
        Product product = productMapper.selectByPrimaryKey(id);
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));
        if (product.getStatus().byteValue() != ProductActivityStatusEnums.UP.getValue()) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.GOODS_NOT_GROUNDING));
        }
        // pv值加+1
        product.setPv(product.getPv() + 1);
        productMapper.updateByPrimaryKeySelective(product);

        // 商品浏览记录
//        ProductBroweRecordResponse productBroweRecord = new ProductBroweRecordResponse();
//        BeanUtils.copyProperties(product, productBroweRecord);
//        productBroweRecord.setProductSource(ProductRecordConstant.ACTIVITY);
//        productBroweRecord.setProductId(product.getId());
//        productBroweRecord.setModular(modular);
//        productBroweRecord.setPageSource(modular);
//        if ("h5".equals(TokenUtil.getRequest().getHeader("source"))) {
//            // h5 才取 token值
//            productBroweRecord.setH5Token(TokenUtil.getRequest().getHeader("token"));
//        }
//        productRecordUtil.productRecord(productBroweRecord);

        ProductImgExample example = new ProductImgExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andProductIdEqualTo(id);
        List<ProductImg> productImgList = productImgMapper.selectByExample(example);
        Map<String, List<ProductImg>> map = productImgList.stream()
                .collect(Collectors.groupingBy(ProductImg::getType));
        ProductResponse productResponse = new ProductResponse(product);
        PageButton pageButton = productService.getPageButton(productResponse.getActivityType());
        productResponse.setPageButton(pageButton);
        pageButton.setCopywriter(productService.getCopywriter(productResponse, null));
        productResponse.setPageButton(pageButton);
        productResponse.setImgMapList(map);
        productResponse.setPreferentialPrice(productResponse.getActivityMax());
        if (ActivityTypeEnums.SECKILL.name().equals(productResponse.getActivityType()) || ActivityTypeEnums.CASH_SCORE.name().equals(productResponse.getActivityType())) {
            productResponse.setPreferentialPrice(productResponse.getOriginalPrice().subtract(productResponse.getPrice()).setScale(0, BigDecimal.ROUND_UP));
        }

        if (ActivityTypeEnums.SECKILL.name().equals(productResponse.getActivityType())) {
            productResponse.setActivityMax(productResponse.getOriginalPrice().subtract(productResponse.getPrice()).setScale(0, BigDecimal.ROUND_UP));
        }
        if (ActivityTypeEnums.CASH_COUPON.name().equals(productResponse.getActivityType())) {
            if (productResponse.getColumnId() == 20) {
                // 50元优惠券
                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(50));
                productResponse.setActivityMax(new BigDecimal(50));
                productResponse.setCurPrice(curPrice);
                productResponse.setPreferentialPrice(new BigDecimal(50));

            }
            if (productResponse.getColumnId() == 21) {
                // 100 元优惠券
                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(100));
                productResponse.setActivityMax(new BigDecimal(100));
                productResponse.setCurPrice(curPrice);
                productResponse.setPreferentialPrice(new BigDecimal(100));
            }
        }
        // 店铺推荐相关信息
        Integer bankerId = productResponse.getBankerId();
        productResponse.setRecommend(productDao.getRecommend(bankerId));
        productResponse.setProductNum(productDao.countProductNumByBankerId(bankerId));
        productResponse.setFollowNum(productDao.countFollowNumByBankerId(bankerId));
        BankerInfoResponse bankerInfoResponse = evaluationProductDao.findBankerInfoByBankerId(bankerId);
        if (bankerInfoResponse != null) {
            productResponse.setTitle(bankerInfoResponse.getTitle());
            productResponse.setLogo(bankerInfoResponse.getLogo());
        }
        return productResponse;
    }

    @Override
    public ProductActivitySpecResponse getActivityProductSpecInfo(Integer productId, String productSpec) {
        Optional.ofNullable(productActivityMapper.selectByPrimaryKey(productId))
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ACTIVITY_COMMODITY_NOT_EXIST)));
        ProductActivitySpecExample example = new ProductActivitySpecExample();
        example.createCriteria()
                .andActivityIdEqualTo(productId)
                .andSkuSpecEqualTo(productSpec);
        ProductActivitySpec productActivitySpec = Optional.ofNullable(productActivitySpecMapper.selectByExample(example))
                .map(item -> item.get(0))
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ACTIVITY_COMMODITY_NOT_STOCK)));
        return new ProductActivitySpecResponse(productActivitySpec);
    }

    @Override
    public ProductActivitySpecResponse getActivityProductSpecById(Integer productSpecId) {
        return new ProductActivitySpecResponse(productActivitySpecMapper.selectByPrimaryKey(productSpecId));
    }

    @Override
    public ScorePageResponse getScoreProductList(UsersResponse user, Integer brandId) {
        ScorePageResponse response = new ScorePageResponse();
        if (user == null) {
            response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        } else {
            UsersDto usersDto = usersClient.getUsersInfo(user.getId());
            response.setScore(usersDto.getScore());
            response.setIsSign(usersClient.isSign(user.getId()));
        }
        response.setDefaultScore(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE));
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andExtraIn(Arrays.asList("SUPER_CHANGE", "CHANGE_SENIORITY", "GET_LIKE"))
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> cashScoreColumn = activityColumnMapper.selectByExample(activityColumnExample);
        Map<String, List<ProductShortResponse>> map = cashScoreColumn.stream()
                .map(item -> {
                    ActivityColumnResponse columnResponse = new ActivityColumnResponse();
                    ProductExample productExample = new ProductExample();
                    productExample.setOrderByClause("sort desc");
                    productExample.createCriteria()
                            .andColumnIdEqualTo(item.getId())
                            .andPlatformDataIn(Arrays.asList("app", "all"))
                            .andDataTypeEqualTo(TokenUtil.getDataType())
                            .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                            .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                                    ProductActivityStatusEnums.PRESELL.getValue()));
                    List<Product> productList = productMapper.selectByExample(productExample);
                    BeanUtils.copyProperties(item, columnResponse);
                    columnResponse.setProductList(productList.stream()
                            .map(ProductShortResponse::new)
                            .collect(Collectors.toList()));
                    return columnResponse;
                })
                .collect(Collectors.toMap(ActivityColumnResponse::getExtra, item -> item.getProductList()));
        // 取出积分兑换商品前 N 个不变其他的打乱
        List<ProductShortResponse> superChangeList = map.get("SUPER_CHANGE");
        if (map != null && !CollectionUtils.isEmpty(superChangeList)) {
            if (brandId == null) {
                String scoreSuperChange = sysConfigUtil.getSysConfig(SysConfigConstants.SCORE_SUPER_CHANGE);
                List<ProductShortResponse> fourList = superChangeList.subList(0, Integer.parseInt(scoreSuperChange));
                List<ProductShortResponse> ortherList = superChangeList.subList(Integer.parseInt(scoreSuperChange), superChangeList.size());
                Collections.shuffle(ortherList);
                List<ProductShortResponse> newList = new ArrayList<>();
                newList.addAll(fourList);
                newList.addAll(ortherList);
                map.remove("SUPER_CHANGE");
                map.put("SUPER_CHANGE", newList);
            } else {
                ProductExample productExample = new ProductExample();
                productExample.createCriteria()
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                        .andIsHideEqualTo(0)
                        .andBankerColumnIdNotIn(Arrays.asList(1, 3))     // 筛选掉 “清仓”、“0元商品‘
                        .andPlatformDataIn(Arrays.asList("app", "all"))
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                                ProductActivityStatusEnums.PRESELL.getValue()));
                List<Product> productList = productMapper.selectByExample(productExample);
                List<ProductShortResponse> newList = productList.stream()
                        .map(ProductShortResponse::new)
                        .collect(Collectors.toList());
                Collections.shuffle(newList);
                map.remove("SUPER_CHANGE");
                map.put("SUPER_CHANGE", newList);
            }
        }
        // 下期预告
//        List<ProductResponse> nextNoticeProductList = map.get("SUPER_CHANGE");
//        if (nextNoticeProductList != null) {
//            Random random = new Random(1);
//            List<ProductResponse> randNextNoticeProductList = new ArrayList<>();
//            ArrayList<Integer> randomed = new ArrayList<>();
//            for (int i = 0; i < 4;) {
//                int randNum = random.nextInt(nextNoticeProductList.size() - 1);
//                if (!randomed.contains(randNum)) {
//                    randNextNoticeProductList.add(nextNoticeProductList.get(randNum));
//                    randomed.add(randNum);
//                    i++;
//                }
//            }
//            response.setNextNoticeList(randNextNoticeProductList);
//        }
        response.setNextNoticeList(new ArrayList<>());

        List<ProductShortResponse> changeSeniorityList = map.get("CHANGE_SENIORITY");
        if (map != null && !CollectionUtils.isEmpty(changeSeniorityList)) {
            changeSeniorityList = changeSeniorityList.stream().filter(item -> item.getIsAdvert() == 0 && item.getIsHide() == 0).collect(Collectors.toList());
        }
        List<ProductShortResponse> getLikeList = map.get("GET_LIKE");
        if (map != null && !CollectionUtils.isEmpty(getLikeList)) {
            getLikeList = getLikeList.stream().filter(item -> item.getIsAdvert() == 0 && item.getIsHide() == 0).collect(Collectors.toList());
        }
        response.setCashScoreColumn(map);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.GET_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andBankerColumnIdNotIn(Arrays.asList(1, 3))     // 筛选掉 “清仓”、“0元商品‘
                .andIsHideEqualTo(0)
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> productList = productMapper.selectByExample(productExample);
        response.setGetScoreList(productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList()));
        return response;
    }

    @Override
    public List<ProductResponse> getActivityCorrelationPro(String activityType, Integer productId) {
        PageHelper.startPage(1, 7);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");

        ProductExample.Criteria criteria = productExample.createCriteria()
                .andStockNotEqualTo(0)
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(activityType)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo(ProductActivityStatusEnums.UP.getValue());
        List<Product> products = productMapper.selectByExample(productExample);
        List<Product> productList = products.stream()
                .filter(product -> !product.getId().equals(productId))
                .limit(6)
                .collect(Collectors.toList());

        return productList.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    if (ActivityTypeEnums.AUCTION.name().equals(productResponse.getActivityType())) {
                        List<AuctionResponse> list = new ArrayList<>();
                        // 最低售价
                        BigDecimal minPrice = item.getActivityMin();
                        // 每次加价幅度
                        BigDecimal maxPrice = item.getActivityMax();
                        List<UsersFake> fakeUserList = getFakeUserList();
                        int count = 0;
                        // 出售价
                        do {
                            if (count != 0) {
                                minPrice = minPrice.add(maxPrice)
                                        .setScale(2, BigDecimal.ROUND_DOWN);
                            }
                            count++;
                            AuctionResponse auctionResponse = new AuctionResponse();
                            UsersFake usersFake = fakeUserList.get((int) Math.round(Math.random() * 9));
                            auctionResponse.setHead(usersFake.getHeadImg());
                            auctionResponse.setUserName(usersFake.getNickname());
                            auctionResponse.setPrice(minPrice);
                            if (-1 != minPrice.compareTo(item.getPrice())) {
                                auctionResponse.setIsSalePrice(IsSalePriceConstant.YES);
                            } else {
                                auctionResponse.setIsSalePrice(IsSalePriceConstant.NO);
                            }
                            list.add(auctionResponse);
                        } while (-1 == minPrice.compareTo(item.getPrice()));

                        // 多给一次拍卖价格，错开机器人拍卖
                        minPrice = minPrice.add(maxPrice)
                                .setScale(2, BigDecimal.ROUND_DOWN);
                        AuctionResponse auctionResponse = new AuctionResponse();
                        UsersFake usersFake = fakeUserList.get((int) Math.round(Math.random() * 9));
                        auctionResponse.setHead(usersFake.getHeadImg());
                        auctionResponse.setUserName(usersFake.getNickname());
                        auctionResponse.setPrice(minPrice);
                        auctionResponse.setIsSalePrice(IsSalePriceConstant.NO);
                        list.add(auctionResponse);
                        productResponse.setAuctionList(list);
                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sellAfter(Integer isDirectbuy, Integer activityId, Integer specId, String activityType, Integer sum, BigDecimal productPrice, BigDecimal activityMax, Integer userId) {
        // 减库存 加销量
        ProductActivity product = productActivityMapper.selectByPrimaryKey(activityId);
        product.setStock(product.getStock() - sum);
        product.setVolume(product.getVolume() + sum);
        productActivityMapper.updateByPrimaryKeySelective(product);
        ProductActivitySpec productSpec = productActivitySpecMapper.selectByPrimaryKey(specId);
        productSpec.setBuySum(productSpec.getBuySum() + sum);
        productSpec.setStock(productSpec.getStock() - sum);
        productActivitySpecMapper.updateByPrimaryKeySelective(productSpec);
        // 加店家销量
        Banker banker = bankerMapper.selectByPrimaryKey(product.getBankerId());
        if (banker != null) {
            banker.setSales(banker.getSales() + sum);
            banker.setSalesMoney(banker.getSalesMoney().add(productPrice).setScale(2));
            bankerMapper.updateByPrimaryKeySelective(banker);
        }
        // 直接购买不做任何操作
        if (isDirectbuy == 0) {
            // 根据活动类型做不同策略
            switch (activityType) {
                case "CASH_SCORE":
                    // 兑换积分的扣积分 加扣积分流水
                    usersClient.subScore(activityMax.intValue(), userId, activityType);
                    break;
                case "GET_SCORE":
                case "NEW_USER":
                    // 新人首单的加积分 加积分流水
                    // 返现积分的加积分 加积分流水
                    usersClient.addScore(activityMax.intValue(), userId, activityType);
                    break;
                case "RETURN_CASH":
                    // 钱包返现 加金额
                    usersClient.addBalance(activityMax, userId, UserBalanceSourceEnums.RETURN_CASH.name());
                    break;
                case "CASH_COUPON":
                    // 优惠券
//                List<UsersCouponDto> usersCoupontList = usersClient.getUsersCoupontList();
//                if(!CollectionUtils.isEmpty(usersCoupontList)){
//                    for(UsersCouponDto item: usersCoupontList){
//                        String coupon = redisService.get(RedisConstants.USERS_COUPON+item.getId()+":"+userId);
//                        if(StringUtils.isNotBlank(coupon)){
//                            UsersCouponDto usersCouponDto = JSONObject.parseObject(coupon,UsersCouponDto.class);
//                            if(usersCouponDto.getMoney().compareTo(new BigDecimal(50)) == 0){
//                                usersCouponDto.setCouponId(20);
//                            }
//                            if(usersCouponDto.getMoney().compareTo(new BigDecimal(100)) == 0){
//                                usersCouponDto.setCouponId(21);
//                            }
//                            if(usersCouponDto.getCouponId() == product.getColumnId()){
//                                usersCouponDto.setIsUse(true);
//                                redisService.set(RedisConstants.USERS_COUPON+item.getId()+":"+userId,JSONObject.toJSONString(usersCouponDto));
//                            }
//                        }
//                    }
//                }
            }
        }

    }

    @Resource
    private ProductSpecMapper productSpecMapper;

    @Override
    public List<ProductSpecResponse> getActivityProductSpecList(Integer productId) {
        ProductSpecExample productSpecExample = new ProductSpecExample();
        productSpecExample.createCriteria().andProductIdEqualTo(productId);
        List<ProductSpec> productSpecList = productSpecMapper.selectByExample(productSpecExample);
        return productSpecList.stream().map(ProductSpecResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public List<ActivityColumnResponse> getCashCouponList() {
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> cashCouponColumns = activityColumnMapper.selectByExample(activityColumnExample);
        List<ActivityColumnResponse> list = cashCouponColumns.stream()
                // 排序
                .sorted((item1, item2) -> {
                    Integer cash1 = item1.getSort();
                    Integer cash2 = item1.getSort();
                    return cash1.compareTo(cash2);
                })
                // 转换组装
                .map(item -> {
                    ActivityColumnResponse response = new ActivityColumnResponse();
                    ProductExample productExample = new ProductExample();
                    productExample.setOrderByClause("sort desc");
                    productExample.createCriteria()
                            .andDataTypeEqualTo(TokenUtil.getDataType())
                            .andColumnIdEqualTo(item.getId())
                            .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                            .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
                    List<Product> products = productMapper.selectByExample(productExample);
                    BeanUtils.copyProperties(item, response);
                    List<ProductShortResponse> collect = products.stream()
                            .map(childItem -> {
                                        ProductShortResponse productResponse = new ProductShortResponse(childItem);
                                        productResponse.setCashCouponImg(item.getExtra());
                                        productResponse.setCashType(childItem.getColumnId().equals(ActivityConstant.FIFTY_CASH_COUPON) ? "0" : "1");
                                        if (ActivityTypeEnums.CASH_COUPON.name().equals(productResponse.getActivityType())) {
                                            if (productResponse.getColumnId() == 20) {
                                                // 50元优惠券
                                                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(50));
                                                productResponse.setCurPrice(curPrice);
                                            }
                                            if (productResponse.getColumnId() == 21) {
                                                // 100 元优惠券
                                                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(100));
                                                productResponse.setCurPrice(curPrice);
                                            }
                                        }
                                        return productResponse;
                                    }
                            )
                            .collect(Collectors.toList());
                    Collections.shuffle(collect);
                    response.setProductList(collect);

                    return response;
                })
                .collect(Collectors.toList());
        return list;
    }

    @Override
    public List<ProductResponse> getAllCashCouponList() {
        // 取出两张优惠券小图
        // 50优惠券
        // ActivityColumn FiveCashCoupon = activityColumnMapper.selectByPrimaryKey(ActivityConstant.FIFTY_CASH_COUPON);
        // 100优惠卷
        // ActivityColumn TenCashCoupon = activityColumnMapper.selectByPrimaryKey(ActivityConstant.HUNDRED_CASH_COUPON);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andIsAdvertEqualTo(0)
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andIsHideEqualTo(0)
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<Product> productList = Optional.ofNullable(productMapper.selectByExample(productExample))
                .orElse(new ArrayList<>());
        return productList.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item, this.getFakeUserList());
//                    if (item.getColumnId().equals(ActivityConstant.FIFTY_CASH_COUPON)) {
//                        productResponse.setCashCouponImg(FiveCashCoupon.getExtra());
//                        productResponse.setCashType(ActivityConstant.FIFTY_CASH_COUPON_TYPE);
//                    }
//                    if (item.getColumnId().equals(ActivityConstant.HUNDRED_CASH_COUPON)) {
//                        productResponse.setCashCouponImg(TenCashCoupon.getExtra());
//                        productResponse.setCashType(ActivityConstant.HUNDRED_CASH_COUPON_TYPE);
//                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
    }

    @Override
    public H5ScorePageResponse getH5ScoreProductList(UsersResponse r, Integer brandId) {
        H5ScorePageResponse response = new H5ScorePageResponse();
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andExtraIn(Arrays.asList("CHANGE_SENIORITY", "GET_LIKE"))
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> cashScoreColumn = activityColumnMapper.selectByExample(activityColumnExample);
        Map<String, List<ProductShortResponse>> map = cashScoreColumn.stream()
                .map(item -> {
                    ActivityColumnResponse columnResponse = new ActivityColumnResponse();
                    ProductExample productExample = new ProductExample();
                    productExample.setOrderByClause("sort desc");
                    productExample.createCriteria()
                            .andColumnIdEqualTo(item.getId())
                            .andDataTypeEqualTo(TokenUtil.getDataType())
                            .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                            .andIsAdvertEqualTo(0)
                            .andIsHideEqualTo(0)
                            .andPlatformDataIn(Arrays.asList("h5", "all"))
                            .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                                    ProductActivityStatusEnums.PRESELL.getValue()));
                    List<Product> products = productMapper.selectByExample(productExample);
                    BeanUtils.copyProperties(item, columnResponse);
                    columnResponse.setProductList(products.stream()
                            .map(ProductShortResponse::new)
                            .collect(Collectors.toList()));
                    return columnResponse;
                })
                .collect(Collectors.toMap(ActivityColumnResponse::getExtra, item -> item.getProductList()));

        response.setCashScoreColumnMap(map);

        ActivityColumnExample example = new ActivityColumnExample();
        example.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andExtraNotIn(Arrays.asList("CHANGE_SENIORITY", "GET_LIKE"))
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> cashScoreColumnV2 = activityColumnMapper.selectByExample(example);

        response.setCashScoreColumn(cashScoreColumnV2.stream().map(item -> {
            ActivityColumnResponse activityColumnResponse = new ActivityColumnResponse();
            BeanUtils.copyProperties(item, activityColumnResponse);
            ProductExample productExample = new ProductExample();
            productExample.setOrderByClause("sort desc");
            if (brandId == null) {
                productExample.createCriteria()
                        .andColumnIdEqualTo(item.getId())
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andIsHideEqualTo(0)
                        .andPlatformDataIn(Arrays.asList("h5", "all"))
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                                ProductActivityStatusEnums.PRESELL.getValue()));
            } else {
                productExample.createCriteria()
                        .andColumnIdIn(Arrays.asList(item.getId(), 24))
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andIsHideEqualTo(0)
                        .andPlatformDataIn(Arrays.asList("h5", "all"))
                        .andIsAdvertEqualTo(0)
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                                ProductActivityStatusEnums.PRESELL.getValue()));
            }
            List<Product> products = productMapper.selectByExample(productExample);
            List<Product> newList = new ArrayList<>();
            String scoreSuperChange = sysConfigUtil.getSysConfig(SysConfigConstants.SCORE_SUPER_CHANGE);
            List<Product> fourList = products.subList(0, Integer.parseInt(scoreSuperChange));
            List<Product> ortherList = products.subList(Integer.parseInt(scoreSuperChange), products.size());
            Collections.shuffle(ortherList);
            newList.addAll(fourList);
            newList.addAll(ortherList);
            activityColumnResponse.setProductList(newList.stream()
                    .map(ProductShortResponse::new)
                    .collect(Collectors.toList()));

            return activityColumnResponse;
        }).collect(Collectors.toList()));

        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.GET_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList("h5", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> products = productMapper.selectByExample(productExample);
        List<ProductResponse> productResponseList = products.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        Collections.shuffle(productResponseList);
        response.setGetScoreList(productResponseList);

        // 下期预告
        List<ActivityColumnResponse> nextNoticeCashScoreColumn = response.getCashScoreColumn();
        for (ActivityColumnResponse activityColumnResponse : nextNoticeCashScoreColumn) {
            if ("SUPER_CHANGE".equals(activityColumnResponse.getExtra())) {
                List<ProductShortResponse> nextNoticeProductList = activityColumnResponse.getProductList();
                if (nextNoticeProductList != null && nextNoticeProductList.size() > 0) {
                    Random random = new Random(1);
                    List<ProductShortResponse> randNextNoticeProductList = new ArrayList<>();
                    ArrayList<Integer> randomed = new ArrayList<>();
                    for (int i = 0; i < 4; ) {
                        int randNum = random.nextInt(nextNoticeProductList.size() - 1);
                        if (!randomed.contains(randNum)) {
                            randNextNoticeProductList.add(nextNoticeProductList.get(randNum));
                            randomed.add(randNum);
                            i++;
                        }
                    }
                    response.setNextNoticeList(randNextNoticeProductList);
                }
            }
        }
        // 导航栏
        response.setActivityNavList(this.getActivityNavList("SCORE_TO_PRO"));
        return response;
    }

    @Override
    public void sellAfter(Integer isDirectbuy, Integer activityId, Integer specId, String activityType, Integer sum, BigDecimal productPrice, BigDecimal activityMax, Integer userId, String tokenUser, Integer isWalletPay) {
        // 减库存 加销量
        ProductActivity product = productActivityMapper.selectByPrimaryKey(activityId);
        product.setStock(product.getStock() - sum);
        product.setVolume(product.getVolume() + sum);
        productActivityMapper.updateByPrimaryKeySelective(product);
        ProductActivitySpec productSpec = productActivitySpecMapper.selectByPrimaryKey(specId);
        productSpec.setBuySum(productSpec.getBuySum() + sum);
        productSpec.setStock(productSpec.getStock() - sum);
        productActivitySpecMapper.updateByPrimaryKeySelective(productSpec);
        // 加店家销量
        Banker banker = bankerMapper.selectByPrimaryKey(product.getBankerId());
        banker.setSales(banker.getSales() + sum);
        banker.setSalesMoney(banker.getSalesMoney().add(productPrice).setScale(2));
        bankerMapper.updateByPrimaryKeySelective(banker);

        UsersResponse token = JSONObject.parseObject(tokenUser, UsersResponse.class);
        if (null != token) {
            if (isWalletPay == 1) {
                token.setMoney(new BigDecimal(0));
            }
        }
        log.debug("购买用户信息：{}", JSONObject.toJSONString(token));
        UsersResponse usersResponse = usersClient.getUsers(userId);
        boolean key = null != usersResponse && usersResponse.getStatus().byteValue() == (byte) 3;

        // 直接购买不做任何操作
        if (isDirectbuy == 0) {
            // 根据活动类型做不同策略
            switch (activityType) {
                case "CASH_SCORE":
                    token.setScore(token.getScore() - activityMax.intValue() <= 0 ? 0 : token.getScore() - activityMax.intValue());
                    if (key) {
                        usersClient.subScore(activityMax.intValue(), userId, activityType);
                    }
                    break;
                case "GET_SCORE":
                case "NEW_USER":
                    // 新人首单的加积分 加积分流水
                    // 返现积分的加积分 加积分流水
                    token.setScore(token.getScore() + activityMax.intValue());
                    if (key) {
                        usersClient.addScore(activityMax.intValue(), userId, activityType);
                    }
                    break;
                case "RETURN_CASH":
                    // 钱包返现 加金额
                    token.setMoney(token.getMoney().add(activityMax).setScale(2));
                    if (key) {
                        usersClient.addBalance(activityMax, userId, activityType);
                    }
                    break;
            }
        }
        log.debug("处理完购买用户信息 : {}", JSONObject.toJSONString(token));
        redisService.set(token.getToken(), JSONObject.toJSONString(token));
        redisService.expire(token.getToken(), TokenConstants.EXPIRE_SECONDS);

    }

//    public List<List<ProductActivityResponse>> getAuctionProductList() {
//        // 取出所有上架的拍卖商品
//        ProductActivityExample productActivityExample = new ProductActivityExample();
//        productActivityExample.createCriteria()
//                .andDataTypeEqualTo(TokenUtil.getDataType())
//                .andPlatformDataIn(Arrays.asList("app","all"))
//                .andActivityTypeEqualTo(ActivityTypeEnums.AUCTION.name())
//                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
//        List<ProductActivity> productActivities = productActivityMapper.selectByExample(productActivityExample);
//        // 打乱顺序
//        Collections.shuffle(productActivities);
//        // 每个拍卖位的商品数量
//        String auctionQuantity = sysConfigUtil.getSysConfig(SysConfigConstants.AUCTION_QUANTITY);
////        // 拍卖位置
//
//        BigDecimal auctionLocation = new BigDecimal(productActivities.size())
//                .divide(new BigDecimal(auctionQuantity), 0, BigDecimal.ROUND_UP);
//        List<ProductActivityResponse> productActivityList = productActivities.stream()
//                .map(item -> {
//                    ProductActivityResponse productActivityResponse = new ProductActivityResponse(item);
//                    List<AuctionResponse> list = new ArrayList<>();
//                    // 最低售价
//                    BigDecimal minPrice = item.getActivityMin();
//                    // 每次加价幅度
//                    BigDecimal maxPrice = item.getActivityMax();
//                    List<UsersFake> fakeUserList = getFakeUserList();
//                    int count = 0;
//                    // 出售价
//                    do {
//                        if (count != 0) {
//                            minPrice = minPrice.add(maxPrice)
//                                    .setScale(2, BigDecimal.ROUND_DOWN);
//                        }
//                        count++;
//                        AuctionResponse auctionResponse = new AuctionResponse();
//                        UsersFake usersFake = fakeUserList.get((int) Math.round(Math.random() * 9));
//                        auctionResponse.setHead(usersFake.getHeadImg());
//                        auctionResponse.setUserName(usersFake.getNickname());
//                        auctionResponse.setPrice(minPrice);
//                        if (-1 != minPrice.compareTo(item.getPrice())) {
//                            auctionResponse.setIsSalePrice(IsSalePriceConstant.YES);
//                        } else {
//                            auctionResponse.setIsSalePrice(IsSalePriceConstant.NO);
//                        }
//                        list.add(auctionResponse);
//                    } while (-1 == minPrice.compareTo(item.getPrice()));
//
//                    // 多给一次拍卖价格，错开机器人拍卖
//                    minPrice = minPrice.add(maxPrice)
//                            .setScale(2, BigDecimal.ROUND_DOWN);
//                    AuctionResponse auctionResponse = new AuctionResponse();
//                    UsersFake usersFake = fakeUserList.get((int) Math.round(Math.random() * 9));
//                    auctionResponse.setHead(usersFake.getHeadImg());
//                    auctionResponse.setUserName(usersFake.getNickname());
//                    auctionResponse.setPrice(minPrice);
//                    auctionResponse.setIsSalePrice(IsSalePriceConstant.NO);
//                    list.add(auctionResponse);
//                    ProductActivitySpecExample example = new ProductActivitySpecExample();
//                    example.createCriteria()
//                            .andActivityIdEqualTo(item.getId());
//                    List<ProductActivitySpec> productActivitySpecs = productActivitySpecMapper.selectByExample(example);
//                    if (productActivitySpecs.size() > 0) {
//                        productActivityResponse.setSpecId(productActivitySpecs.get(0).getId());
//                    }
//                    productActivityResponse.setAuctionList(list);
//                    return productActivityResponse;
//                })
//                .collect(Collectors.toList());
//
//        List<List<ProductActivityResponse>> responses = PageUtils.averageAssign(productActivityList, auctionLocation.intValue());
//        return responses;
//    }

    @Override
    public MaxNavResponse getActivityNavList(String type) {
        NavExample navExample = new NavExample();
        if ("h5".equals(TokenUtil.getRequest().getHeader("source"))) {
            navExample.createCriteria()
                    .andPlatformEqualTo("h5")
                    .andTypeEqualTo(type);
        } else {
            navExample.createCriteria()
                    .andPlatformEqualTo("app")
                    .andTypeEqualTo(type);
        }

        List<Nav> navList = Optional.ofNullable(navMapper.selectByExample(navExample))
                .orElse(new ArrayList<>());
        if ("v3".equals(TokenUtil.getRequest().getHeader("api-ver"))) {
            navList = navList.stream().map(item -> {
                item.setPath(PathUtils.replaceUrl(item.getPath()));
                return item;
            })
                    .collect(Collectors.toList());
        }
        List<NavResponse> NavResponseList = navList.stream()
                .sorted(Comparator.comparing(Nav::getSort))
                .map(NavResponse::new)
                .collect(Collectors.toList());
        MaxNavResponse maxNavResponse = new MaxNavResponse();
        maxNavResponse.setNavResponseList(NavResponseList);
        maxNavResponse.setColor(NavResponseList != null && NavResponseList.size() > 0 ? NavResponseList.get(0).getColor() : null);
        return maxNavResponse;
    }

    @Override
    public List<Banners> getActivityBannerList() {
        BannersExample bannersExample = new BannersExample();
        bannersExample.createCriteria()
                .andTypeEqualTo("ACTIVITY")
                .andStatusEqualTo((byte) 1);
        List<Banners> bannerList = Optional.ofNullable(bannersMapper.selectByExample(bannersExample))
                .orElse(new ArrayList<>());
        if ("v3".equals(TokenUtil.getRequest().getHeader("api-ver"))) {
            bannerList = bannerList.stream().map(item -> {
                item.setAPath(PathUtils.replaceUrl(item.getAPath()));
                return item;
            }).collect(Collectors.toList());
        }
        return bannerList.stream()
                .sorted(Comparator.comparing(Banners::getSort))
                .collect(Collectors.toList());
    }

    @Override
    public ActivityCashCouponResponse getCouponProductList(Integer userId) {
        ActivityCashCouponResponse activityCashCouponResponse = new ActivityCashCouponResponse();

        // 查询所有优惠券
        List<UsersCouponDto> usersCoupontList = usersClient.getUsersCoupontList();
        usersCoupontList = usersCoupontList.stream().map(item -> {
            String coupon = redisService.get(RedisConstants.USERS_COUPON + item.getId() + ":" + userId);
            item.setIsReceive(false);
            if (StringUtils.isNotBlank(coupon)) {
                UsersCouponDto usersCouponDto = JSONObject.parseObject(coupon, UsersCouponDto.class);
                // 是否领取
                item.setIsReceive(true);
                // 是否被使用
                item.setIsUse(usersCouponDto.getIsUse());
                // 过期时间 毫秒
                long overdueTime = usersCouponDto.getOverdueTime();
                if (overdueTime <= System.currentTimeMillis()) {
                    item.setOverdueTime(0);
                } else {
                    item.setOverdueTime(overdueTime);
                }
            }
            return item;
        }).collect(Collectors.toList());
        activityCashCouponResponse.setUsersCouponDtos(usersCoupontList);

        // 查询所有栏目商品列表
        List<ActivityColumnResponse> cashCouponList = this.getCashCouponList();
        activityCashCouponResponse.setActivityColumnList(cashCouponList);

        // 查询所有活动商品
        List<ProductResponse> allCashCouponList = this.getAllCashCouponList();
        activityCashCouponResponse.setProductActivityList(allCashCouponList);

        return activityCashCouponResponse;
    }

    @Override
    public ActivityCashCouponResponse getCouponProductNewList(Integer userId) {
        ActivityCashCouponResponse activityCashCouponResponse = new ActivityCashCouponResponse();
        // 查询该用户所有优惠券信息
        List<UsersCouponRelationDto> usersCoupontList = null;
        if ("h5".equals(TokenUtil.getRequest().getHeader("source"))||"quick-app".equals(TokenUtil.getSource())) {
            usersCoupontList = usersClient.getUsersCoupontRelationList();
        } else {
            usersCoupontList = usersClient.getUsersCoupontRelationList(userId);
        }
        activityCashCouponResponse.setUsersCouponRelationDtos(usersCoupontList);

        // 查询所有栏目商品列表
        List<ActivityColumnResponse> cashCouponList = this.getCashCouponList();
        activityCashCouponResponse.setActivityColumnList(cashCouponList);

        // 查询所有活动商品
        List<ProductResponse> allCashCouponList = this.getAllCashCouponList();
        activityCashCouponResponse.setProductActivityList(allCashCouponList);

        return activityCashCouponResponse;

    }

    @Override
    public ActivityCashCouponResponse getAllCouponList() {
        ActivityCashCouponResponse activityCashCouponResponse = new ActivityCashCouponResponse();
        // 获取所有优惠券列表
        List<UsersCouponRelationDto> usersCoupontList = usersClient.getUsersCoupontRelationList();
        usersCoupontList = usersCoupontList.stream().map(item -> {
            // 过期时间/优惠券说明  暂时写死
            item.setExpireTime("2020.12.01-2020-12.31");
            item.setExplain("全品类可用，新品可用：除详情页标注不可用券的商品除外");
            return item;
        }).collect(Collectors.toList());
        activityCashCouponResponse.setUsersCouponRelationDtos(usersCoupontList);
        return activityCashCouponResponse;
    }

    @Override
    public List<ProductResponse> getCouponProductListById(Integer id, Integer pageNum, Integer pageSize) {
        String source = TokenUtil.getSource();
        // 查询该优惠券下所有的商品
        PageHelper.startPage(pageNum, pageSize);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        if (id == 20) {
            if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
                productExample.createCriteria()
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andPlatformDataIn(Arrays.asList("h5", "all"))
                        .andActivityMaxEqualTo(new BigDecimal(50))
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
            } else {
                productExample.createCriteria()
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andPlatformDataIn(Arrays.asList("app", "all"))
                        .andActivityMaxEqualTo(new BigDecimal(50))
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
            }
        }
        if (id == 21) {
            if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
                productExample.createCriteria()
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andPlatformDataIn(Arrays.asList("h5", "all"))
                        .andActivityMaxEqualTo(new BigDecimal(100))
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
            } else {
                productExample.createCriteria()
                        .andDataTypeEqualTo(TokenUtil.getDataType())
                        .andPlatformDataIn(Arrays.asList("app", "all"))
                        .andActivityMaxEqualTo(new BigDecimal(100))
                        .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                        .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
            }
        }
        List<Product> products = productMapper.selectByExample(productExample);
        List<ProductResponse> cashCouponList = products.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        Collections.shuffle(cashCouponList);
        return cashCouponList;
    }

    @Override
    public List<ProductResponse> getCouponListV1() {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andIdIn(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.COUPON_PRODUCT_V1_PRODUCT_LIST)))
//                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
//                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()))
        ;
        List<Product> products = productMapper.selectByExample(productExample);
        List<ProductResponse> cashCouponList = products.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    try {
                        BigDecimal baseStock = new BigDecimal(Optional.ofNullable(productResponse.getStock()%17).orElse(0))
                                .multiply(new BigDecimal(100))
                                .divide(new BigDecimal(5678), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal stockProgress = new BigDecimal(1)
                                .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                        if(stockProgress.intValue()>=100||stockProgress.intValue()<=0){
                            productResponse.setStockProgress(60);
                        }else {
                            productResponse.setStockProgress(stockProgress.intValue());
                        }
                    } catch (ApiException e) {
                        productResponse.setStockProgress(80);
                    }
                    int i = RandomUtil.getSectionNum(1, 3);
                    switch (i) {
                        case 1:
                            productResponse.setTips("限时限量");
                            break;
                        case 2:
                            productResponse.setTips("7天无理由退换");
                            break;
                        case 3:
                            productResponse.setTips("顺丰包邮");
                            break;
                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
        return cashCouponList;
    }

    @Override
    public List<ProductResponse> getCouponList() {
        // 查询该优惠券下所有的商品
        List<ProductResponse> cashCouponList = this.getCashCoupon();
        // 优惠券置顶数量
        List<ProductResponse> allList = new ArrayList<>();
        Integer cashCouponTopNum = Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.CASH_COUPON_TOP_NUM));
        List<ProductResponse> couponTopList = cashCouponList.stream()
                .limit(cashCouponTopNum)
                .collect(Collectors.toList());
        Collections.shuffle(couponTopList);
        allList.addAll(couponTopList);
        if (cashCouponList.size() > cashCouponTopNum) {
            List<ProductResponse> couponList = cashCouponList.subList(cashCouponTopNum, cashCouponList.size());
            Collections.shuffle(couponList);
            allList.addAll(couponList);
        }
        return allList;
    }

    @Override
    public UserCouponResponse getUserCouponList(Integer type) {
        UserCouponResponse userCouponResponse = new UserCouponResponse();
        List<ProductResponse> result = null;
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Date nowDate = new Date();

        // 查询待使用的优惠券
        List<CouponRecords> useList = couponRecordsDao.selectUsage(0, token, nowDate, source);
        BigDecimal totelPrice = new BigDecimal(0);
        switch (type) {
            case 0:
                result = useList.stream()
                        .map(item -> {
                            Product product = productMapper.selectByPrimaryKey(item.getProductId());
                            ProductResponse productResponse = new ProductResponse(product);
                            productResponse.setIsReceive(2);
                            productResponse.setOverdueTime(item.getOverdueTime());
                            return productResponse;
                        }).collect(Collectors.toList());
                break;
            case 2:
                // 查询过期的前三条
                List<CouponRecords> notUseList = couponRecordsDao.selectUsage(type, token, nowDate, source);
                result = notUseList.stream()
                        .map(item -> {
                            Product product = productMapper.selectByPrimaryKey(item.getProductId());
                            ProductResponse productResponse = new ProductResponse(product);
                            productResponse.setOverdueTime(item.getOverdueTime());
                            return productResponse;
                        }).collect(Collectors.toList());
                break;
        }
        if (!CollectionUtils.isEmpty(useList)) {
            for (CouponRecords item : useList) {
                Product product = productMapper.selectByPrimaryKey(item.getProductId());
                // 累加优惠券金额
                totelPrice = totelPrice.add(product.getActivityMax());
            }
        }
        userCouponResponse.setCouponList(result);
        userCouponResponse.setTotelPrice(totelPrice.setScale(2, BigDecimal.ROUND_UP));
        return userCouponResponse;
    }

    /**
     * 领取优惠券
     *
     * @param productId
     * @return
     */
    @Override
    public CouponRecords obtainCoupon(Integer productId) {
        Date date = new Date();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Integer count = couponRecordsDao.selectIsReceive(productId, token, date, source);
        if (count > 0) {
            throw new ApiException("该优惠券已经领取,请勿重复领取!");
        }

        int couponExpirationTime = RandomUtil.getSectionNum(20, 40);
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, couponExpirationTime);
        // 当前时间 + 过期时间
        Date overdueTime = nowTime.getTime();

        CouponRecords couponRecords = new CouponRecords();
        couponRecords.setProductId(productId);
        couponRecords.setSource(source);
        couponRecords.setToken(token);
        // 领取时间
        couponRecords.setReceiveTime(date);
        // 到期时间
        couponRecords.setOverdueTime(overdueTime);
        // 时长
        couponRecords.setDurationTime(couponExpirationTime);
        couponRecordsMapper.insert(couponRecords);
        return couponRecords;
    }

    public CouponRecords obtainCouponv2(Integer productId) {
        Date date = new Date();
        String token;
        String source = TokenUtil.getSource();
        if ("h5".equals(source)||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Integer count = couponRecordsDao.selectIsReceive(productId, token, date, source);
        if (count > 0) {
            CouponRecords couponRecords = couponRecordsDao.queryOne(productId, token, date, source);
            return couponRecords;
        }

        int couponExpirationTime = RandomUtil.getSectionNum(20, 40);
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, couponExpirationTime);
        // 当前时间 + 过期时间
        Date overdueTime = nowTime.getTime();

        CouponRecords couponRecords = new CouponRecords();
        couponRecords.setProductId(productId);
        couponRecords.setSource(source);
        couponRecords.setToken(token);
        // 领取时间
        couponRecords.setReceiveTime(date);
        // 到期时间
        couponRecords.setOverdueTime(overdueTime);
        // 时长
        couponRecords.setDurationTime(couponExpirationTime);
        couponRecordsMapper.insert(couponRecords);
        return couponRecords;
    }

    @Override
    public UserCouponResponse getCouponListV2() {
        UserCouponResponse userCouponResponse = new UserCouponResponse();
        // 未使用的优惠券商品id
        String notUseCoupon = sysConfigUtil.getSysConfig(SysConfigConstants.NOT_USE_COUPON);
        List<Integer> ids = this.convertType(notUseCoupon);
        // 查询该优惠券下所有的商品
        ProductExample productExample = new ProductExample();
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andIdIn(ids)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> products = productMapper.selectByExample(productExample);
        List<ProductResponse> cashCouponList = this.convertData(products);

        userCouponResponse.setCouponList(cashCouponList);
//        // 配置的未使用优惠券
        List<Product> notuseProduct = products.stream()
                .filter(item -> !ids.contains(item.getId()))
                .collect(Collectors.toList());
        List<ProductResponse> notuseList = this.convertData(notuseProduct);
        userCouponResponse.setNotUseCoupon(notuseList);
        // 待使用总价格
        BigDecimal totelPrice = new BigDecimal(0);
        if (!CollectionUtils.isEmpty(cashCouponList)) {
            for (ProductResponse item : cashCouponList) {
                // 累加优惠券金额
                totelPrice = totelPrice.add(item.getActivityMax());
            }
        }
        userCouponResponse.setTotelPrice(totelPrice);
        return userCouponResponse;
    }

    // 字符串数组转整数集合
    private List<Integer> convertType(String config) {
        String[] str = config.split(",");
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            ids.add(Integer.parseInt(str[i]));
        }
        return ids;
    }

    private List<ProductResponse> convertData(List<Product> products) {
        List<ProductResponse> cashCouponList = products.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    try {
                        BigDecimal baseStock = new BigDecimal(Optional.ofNullable(productResponse.getStock()%17).orElse(0))
                                .multiply(new BigDecimal(100))
                                .divide(new BigDecimal(5678), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal stockProgress = new BigDecimal(1)
                                .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                        if(stockProgress.intValue()>=100||stockProgress.intValue()<=0){
                            productResponse.setStockProgress(60);
                        }else {
                            productResponse.setStockProgress(stockProgress.intValue());
                        }
                    } catch (ApiException e) {
                        productResponse.setStockProgress(80);
                    }
                    int i = RandomUtil.getSectionNum(1, 3);
                    switch (i) {
                        case 1:
                            productResponse.setTips("限时限量");
                            break;
                        case 2:
                            productResponse.setTips("7天无理由退换");
                            break;
                        case 3:
                            productResponse.setTips("顺丰包邮");
                            break;
                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
        return cashCouponList;
    }

    @Override
    public UsersCouponDto receiveCoupon(Integer userId, Integer couponId) {
        // 过期时长
        String receiveTime = sysConfigUtil.getSysConfig(SysConfigConstants.RECEIVE_TIME);

        // 天转为秒
        long expireTime = Long.parseLong(receiveTime) * 60 * 60;

        long currentTime = System.currentTimeMillis();

        // 领取 保存到缓存中
        UsersCouponDto usersCouponDto = usersClient.getUsersCouponById(couponId);
        usersCouponDto.setReceiveTime(new Date());
        usersCouponDto.setIsReceive(true);
        usersCouponDto.setIsUse(false);
        usersCouponDto.setOverdueTime(currentTime + expireTime * 1000);
        redisService.set(RedisConstants.USERS_COUPON + couponId + ":" + userId, JSONObject.toJSONString(usersCouponDto));
        redisService.expire(RedisConstants.USERS_COUPON + couponId + ":" + userId, expireTime);
        return usersCouponDto;
    }

    @Override
    public void receiveCouponNew(Integer userId, Integer couponId) {
        usersClient.receiveCoupon(userId, couponId);
    }


    @Override
    public Map<String, ActivityColumnResponse> getSubsidyList() {
        ActivityColumnExample activityColumnExample = new ActivityColumnExample();
        activityColumnExample.setOrderByClause("sort desc");
        activityColumnExample.createCriteria()
                .andTypeEqualTo(ActivityTypeEnums.SUBSIDY.name())
                .andStatusEqualTo(ActivityColumnStatusEnums.UP.getValue());
        List<ActivityColumn> activityColumns = activityColumnMapper.selectByExample(activityColumnExample);
        return activityColumns.stream().map(item -> {
            ActivityColumnResponse response = new ActivityColumnResponse();
            ProductExample productExample = new ProductExample();
            productExample.setOrderByClause("sort desc");
            productExample.createCriteria()
                    .andColumnIdEqualTo(item.getId())
                    .andPlatformDataIn(Arrays.asList("app", "all"))
                    .andDataTypeEqualTo(TokenUtil.getDataType())
                    .andActivityTypeEqualTo(ActivityTypeEnums.SUBSIDY.name())
                    .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                            ProductActivityStatusEnums.PRESELL.getValue()));
            List<Product> products = productMapper.selectByExample(productExample);
            BeanUtils.copyProperties(item, response);
            response.setProductList(products.stream()
                    .map(ProductShortResponse::new)
                    .collect(Collectors.toList()));
            return response;
        }).collect(Collectors.toMap(ActivityColumnResponse::getExtra, item -> item));
    }

    @Override
    public List<ProductResponse> getSeckillRank(Integer columnId) {
        String rankSum = sysConfigUtil.getSysConfig(SysConfigConstants.RANK_SUM);
        PageHelper.startPage(1, Integer.valueOf(rankSum));
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("volume desc");
        productExample.createCriteria()
                .andColumnIdEqualTo(columnId)
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andActivityTypeEqualTo(ActivityTypeEnums.SECKILL.name())
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> products = productMapper.selectByExample(productExample);
        return products.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
    }


    @Override
    public ProductResponse getActivityProductInfoV2(Integer productId, String type, UsersResponse usersResponse, String modular) {
        Product product = productMapper.selectByPrimaryKey(productId);
        Optional.ofNullable(product)
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST)));
        if (product.getStatus().byteValue() != ProductActivityStatusEnums.UP.getValue()) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.GOODS_NOT_GROUNDING));
        }
        // pv值加+1
        product.setPv(product.getPv() + 1);
        productMapper.updateByPrimaryKeySelective(product);

        // 商品浏览记录
        ProductBroweRecordResponse productBroweRecord = new ProductBroweRecordResponse();
        BeanUtils.copyProperties(product, productBroweRecord);
        productBroweRecord.setUserId(usersResponse.getId());
        productBroweRecord.setProductId(product.getId());
        productBroweRecord.setProductSource(ProductRecordConstant.ACTIVITY);
        productBroweRecord.setModular(modular);
        productBroweRecord.setPageSource(modular);
        productRecordUtil.productRecord(productBroweRecord);

        ProductImgExample example = new ProductImgExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andProductIdEqualTo(productId);
        List<ProductImg> productImgList = productImgMapper.selectByExample(example);
        Map<String, List<ProductImg>> map = productImgList.stream()
                .collect(Collectors.groupingBy(ProductImg::getType));
        ProductResponse productResponse = new ProductResponse(product);
        PageButton pageButton = Optional.ofNullable(productService.getPageButton(productResponse.getActivityType()))
                .orElseThrow(() -> new ApiException("pageButton为空"));
        productResponse.setPageButton(pageButton);
        pageButton.setCopywriter(productService.getCopywriter(productResponse, usersResponse));
        productResponse.setPageButton(pageButton);
        productResponse.setImgMapList(map);
        productResponse.setPreferentialPrice(productResponse.getActivityMax());
        if (ActivityTypeEnums.SECKILL.name().equals(productResponse.getActivityType()) || ActivityTypeEnums.CASH_SCORE.name().equals(productResponse.getActivityType())) {
            productResponse.setPreferentialPrice(productResponse.getOriginalPrice().subtract(productResponse.getPrice()).setScale(0, BigDecimal.ROUND_UP));
        }

        if (ActivityTypeEnums.SECKILL.name().equals(productResponse.getActivityType())) {
            productResponse.setActivityMax(productResponse.getOriginalPrice().subtract(productResponse.getPrice()).setScale(0, BigDecimal.ROUND_UP));
        }
        if (ActivityTypeEnums.CASH_COUPON.name().equals(productResponse.getActivityType())) {
            if (productResponse.getColumnId() == 20) {
                // 50元优惠券
                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(50));
                productResponse.setActivityMax(new BigDecimal(50));
                productResponse.setCurPrice(curPrice);
                productResponse.setPreferentialPrice(new BigDecimal(50));
            }
            if (productResponse.getColumnId() == 21) {
                // 100 元优惠券
                BigDecimal curPrice = productResponse.getPrice().add(new BigDecimal(100));
                productResponse.setActivityMax(new BigDecimal(100));
                productResponse.setCurPrice(curPrice);
                productResponse.setPreferentialPrice(new BigDecimal(100));
            }
        }
        // 店铺推荐相关信息
        Integer bankerId = productResponse.getBankerId();
        productResponse.setRecommend(productDao.getRecommend(bankerId));
        productResponse.setProductNum(productDao.countProductNumByBankerId(bankerId));
        productResponse.setFollowNum(productDao.countFollowNumByBankerId(bankerId));
        BankerInfoResponse bankerInfoResponse = evaluationProductDao.findBankerInfoByBankerId(bankerId);
        if (bankerInfoResponse != null) {
            productResponse.setTitle(bankerInfoResponse.getTitle());
            productResponse.setLogo(bankerInfoResponse.getLogo());
        }
        return productResponse;
    }

    @Override
    public List<FakeNoticeResponse> buyNotice() {
        List<Object> fakeUserList = redisService.range(com.ytjj.qmyx.mall.constants.RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> list = fakeUserList.stream()
                .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                .limit(10)
                .collect(Collectors.toList());

        ProductActivityExample activityExample = new ProductActivityExample();
        activityExample.createCriteria()
                .andStatusEqualTo(ProductStatusEnums.UP.getValue())
                .andActivityTypeEqualTo(ActivityTypeEnums.SECKILL.name());
        List<ProductActivity> productActivityList = productActivityMapper.selectByExample(activityExample);
        Random random = new Random();
        return list.stream().map(item -> {
            FakeNoticeResponse fakeNoticeResponse = new FakeNoticeResponse();
            BeanUtils.copyProperties(item, fakeNoticeResponse);
            int n = random.nextInt(productActivityList.size());
            fakeNoticeResponse.setProductName(productActivityList.get(n).getProductName());
            int time = new Random().nextInt(10) + 1;
            fakeNoticeResponse.setTime(String.valueOf(time));
            return fakeNoticeResponse;
        }).collect(Collectors.toList());

    }

    @Override
    public List<ProductActivityImg> getRecommendImgById(Integer id) {
        ProductActivityImgExample example = new ProductActivityImgExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andTypeEqualTo(SpecialTypeEnums.recommend.name())
                .andProductIdEqualTo(id);
        List<ProductActivityImg> productImgList = productActivityImgMapper.selectByExample(example);
        return productImgList;
    }

    @Override
    public NewKillResponse getNewKillList() {
        String RankNum = sysConfigUtil.getSysConfig(SysConfigConstants.KILL_RANK);
        // 假用户
        List<UsersFake> fakeUserList = fakeUserUtil.getFakeUserList();
        List<Product> newKillProductList = productDao.getNewKillProductList(TokenUtil.getDataType(), TokenUtil.getPlatformData());
        List<ProductResponse> rankList = newKillProductList.stream()
                .filter(item -> item.getIsAdvert() == 0 && item.getIsHide() == 0)
                .limit(Integer.valueOf(RankNum))
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    // 随机生成 库存进度码
                    productResponse.setStockProgress(RandomUtil.getSectionNum(10, 20));
                    return productResponse;
                })
                .collect(Collectors.toList());
        List<ProductResponse> killList = newKillProductList.stream()
                .filter(item -> item.getIsAdvert() == 0 && item.getIsHide() == 0)
                .skip(Integer.valueOf(RankNum))
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        // 广告推荐商品
        List<ProductResponse> advertList = newKillProductList.stream()
                .filter(item -> item.getIsAdvert() == 1)
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        NewKillResponse newKillResponse = new NewKillResponse();
        newKillResponse.setFakeUserList(fakeUserList);
        newKillResponse.setRankList(rankList);
        newKillResponse.setKillList(killList);
        newKillResponse.setAdvertList(advertList);
        return newKillResponse;
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5
     *
     * @return
     */
    @Override
    public H5ScorePageResponse getH5ScoreListByColumn(String type) {
        H5ScorePageResponse response = new H5ScorePageResponse();
        // 免费兑商品
        ProductExample freeProductExample = new ProductExample();
        freeProductExample.setOrderByClause("sort desc");
        freeProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andColumnIdEqualTo(25)
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList("h5", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> freeProducts = productMapper.selectByExample(freeProductExample);
        List<ProductResponse> resultTypeProduct = new ArrayList<>();
        // 分不同积分栏目
        ProductExample activityProductExample = new ProductExample();
        activityProductExample.setOrderByClause("sort desc");
        ProductExample.Criteria criteria = activityProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList("h5", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        switch (type) {
            case "SUPER_CHANGE":
                criteria.andColumnIdEqualTo(8);
                List<Product> superProducts = productMapper.selectByExample(activityProductExample);
                superProducts.addAll(freeProducts);
                resultTypeProduct = superProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                Collections.shuffle(resultTypeProduct);
                break;
            case "CHANGE_SENIORITY":
                criteria.andColumnIdEqualTo(9);
                List<Product> changeProducts = productMapper.selectByExample(activityProductExample);
                resultTypeProduct = changeProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                int i = 1;
                for (ProductResponse productResponse : resultTypeProduct) {
                    productResponse.setSort(i++);
                }
                break;
            case "GET_LIKE":
                criteria.andColumnIdEqualTo(10);
                List<Product> getProducts = productMapper.selectByExample(activityProductExample);
                getProducts.addAll(freeProducts);
                resultTypeProduct = getProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                Collections.shuffle(resultTypeProduct);
                break;
            case "ALL":
                List<Product> allProducts = productMapper.selectByExample(activityProductExample);
                List<ProductResponse> tempProducts = allProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                int cashScoreTopNum = Integer.parseInt(sysConfigUtil.getSysConfig(SysConfigConstants.CASH_SCORE_TOP_NUM));
                int j = 1;
                for (ProductResponse productResponse : tempProducts) {
                    if (9 == productResponse.getColumnId()) {
                        productResponse.setSort(j++);
                    }
                }
                List<ProductResponse> topProducts = tempProducts.subList(0, cashScoreTopNum);
                Collections.shuffle(topProducts);
                resultTypeProduct.addAll(topProducts);
                if (tempProducts.size() > cashScoreTopNum) {
                    List<ProductResponse> laterProducts = tempProducts.subList(cashScoreTopNum, tempProducts.size());
                    Collections.shuffle(laterProducts);
                    resultTypeProduct.addAll(laterProducts);
                }
                break;
        }

        response.setGetScoreList(resultTypeProduct);
        // 导航栏
        response.setActivityNavList(this.getActivityNavList("SCORE_TO_PRO"));
        return response;
    }

    @Override
    public ScorePageResponse getScoreListByColumn(UsersResponse user, String type) {
        ScorePageResponse response = new ScorePageResponse();
        if (user == null) {
            response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
        } else {
            UsersDto usersDto = usersClient.getUsersInfo(user.getId());
            response.setScore(usersDto.getScore());
            response.setIsSign(usersClient.isSign(user.getId()));
        }
        response.setDefaultScore(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE));
        // 免费兑商品
        ProductExample freeProductExample = new ProductExample();
        freeProductExample.setOrderByClause("sort desc");
        freeProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andColumnIdEqualTo(25)
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> freeProducts = productMapper.selectByExample(freeProductExample);
        List<ProductResponse> resultTypeProduct = new ArrayList<>();

        ProductExample activityProductExample = new ProductExample();
        activityProductExample.setOrderByClause("sort desc");
        ProductExample.Criteria criteria = activityProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList("app", "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        switch (type) {
            case "SUPER_CHANGE":
                criteria.andColumnIdEqualTo(8);
                List<Product> superProducts = productMapper.selectByExample(activityProductExample);
                superProducts.addAll(freeProducts);
                resultTypeProduct = superProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                Collections.shuffle(resultTypeProduct);
                break;
            case "CHANGE_SENIORITY":
                criteria.andColumnIdEqualTo(9);
                List<Product> changeProducts = productMapper.selectByExample(activityProductExample);
                resultTypeProduct = changeProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                int i = 1;
                for (ProductResponse productResponse : resultTypeProduct) {
                    productResponse.setSort(i++);
                }
                break;
            case "GET_LIKE":
                criteria.andColumnIdEqualTo(10);
                List<Product> getProducts = productMapper.selectByExample(activityProductExample);
                getProducts.addAll(freeProducts);
                resultTypeProduct = getProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                Collections.shuffle(resultTypeProduct);
                break;
            case "ALL":
                List<Product> allProducts = productMapper.selectByExample(activityProductExample);
                List<ProductResponse> tempProducts = allProducts.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                int cashScoreTopNum = Integer.parseInt(sysConfigUtil.getSysConfig(SysConfigConstants.CASH_SCORE_TOP_NUM));
                int j = 1;
                for (ProductResponse productResponse : tempProducts) {
                    if (9 == productResponse.getColumnId()) {
                        productResponse.setSort(j++);
                    }
                }
                List<ProductResponse> topProducts = tempProducts.subList(0, cashScoreTopNum);
                Collections.shuffle(topProducts);
                resultTypeProduct.addAll(topProducts);
                if (tempProducts.size() > cashScoreTopNum) {
                    List<ProductResponse> laterProducts = tempProducts.subList(cashScoreTopNum, tempProducts.size());
                    Collections.shuffle(laterProducts);
                    resultTypeProduct.addAll(laterProducts);
                }
                break;
        }
        response.setGetScoreList(resultTypeProduct);
        return response;
    }

    @Override
    public List<ProductResponse> getProductsByActivityMax(BigDecimal activityMax) {
        ProductExample getProductExample = new ProductExample();
        getProductExample.setOrderByClause("sort desc");
        getProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andActivityMaxEqualTo(activityMax)
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> getProducts = productMapper.selectByExample(getProductExample);
        return getProducts.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public UserCouponResponse getUserCouponListV2(Integer type) {
        UserCouponResponse userCouponResponse = new UserCouponResponse();
        List<ProductResponse> result = null;
        String token = TokenUtil.getUuid();
        String source = TokenUtil.getSource();
        Date nowDate = new Date();

        // 未使用的优惠券商品id
        String notUseCoupon = sysConfigUtil.getSysConfig(SysConfigConstants.NOT_USE_COUPON);
        List<Integer> ids = this.convertType(notUseCoupon);

        log.debug("ids : {}", ids);
        // 查询该优惠券下所有的商品
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("activity_max desc");
        productExample.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andIdIn(ids)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> products = productMapper.selectByExample(productExample);
        List<ProductResponse> cashCouponList = this.convertData(products);
        log.debug("查询出来的数据 : {}", JSONObject.toJSONString(cashCouponList));
        BigDecimal totelPrice = new BigDecimal(0);
        switch (type) {
            case 0:
                result = cashCouponList.stream().map(item -> {
                    CouponRecords couponRecords = this.obtainCouponv2(item.getId());
                    item.setOverdueTime(couponRecords.getOverdueTime());
                    item.setIsReceive(2);
                    return item;
                }).collect(Collectors.toList());
                break;
            case 2:
                // 查询过期的前三条
                List<CouponRecords> notUseList = couponRecordsDao.selectUsage(type, token, nowDate, source);
                result = notUseList.stream()
                        .map(item -> {
                            Product product = productMapper.selectByPrimaryKey(item.getProductId());
                            ProductResponse productResponse = new ProductResponse(product);
                            productResponse.setOverdueTime(item.getOverdueTime());
                            return productResponse;
                        }).collect(Collectors.toList());
                break;
        }

        for (ProductResponse item : cashCouponList) {
            // 累加优惠券金额
            totelPrice = totelPrice.add(item.getActivityMax());
        }
        userCouponResponse.setCouponList(result);
        userCouponResponse.setTotelPrice(totelPrice.setScale(2, BigDecimal.ROUND_UP));
        return userCouponResponse;
    }

    @Override
    public UserCenterResponse getUserCenterData() {
        UserCenterResponse userCenterResponse = new UserCenterResponse();
        PageHelper.startPage(1, 3);
        ProductExample superProductExample = new ProductExample();
        superProductExample.setOrderByClause("sort desc");
        superProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> superProducts = productMapper.selectByExample(superProductExample);
        // sort 排序取出三个
        List<ProductResponse> result = superProducts.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        userCenterResponse.setProductList(result);
        return userCenterResponse;
    }

    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @param flag
     * @return
     */
    @Override
    public H5ScorePageResponse getH5ScoreListByType(Integer flag) {
        H5ScorePageResponse response = new H5ScorePageResponse();

        response.setCashScoreColumnMap(
                this.getCashScoreColumn(
                        this.getCashScoreProductsByScore(flag)
                        , this.getScoreProductsByColumnId(VERY_SCORE_COLUMN_ID)));
        // 导航栏
        response.setActivityNavList(
                this.getActivityNavList("SCORE_TO_PRO"));
        // 品牌列表
        BrandExample brandExample = new BrandExample();
        brandExample.setOrderByClause("sort desc");
        brandExample.createCriteria().andStatusEqualTo(1);
        List<Brand> brandList = brandMapper.selectByExample(brandExample);
        response.setBrandList(brandList);

        // 假用户
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> usersFake = fakeUserList.stream()
                .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                .limit(20)
                .collect(Collectors.toList());
        response.setUsersFakes(usersFake);
        // 假用户数量
        response.setUsersNum(RandomUtil.getSectionNum(700, 1000));

        return response;
    }
    /**
     * 根据不同积分活动栏目获取h5积分产品列表 h5, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @param flag
     * @return
     */
    @Override
    public H5ScorePageResponse getH5ScoreListByTypeForRemote(Integer flag) {
        H5ScorePageResponse response = new H5ScorePageResponse();

        response.setCashScoreColumnMap(
                this.getCashScoreColumnForRemote(
                        this.getCashScoreProductsByScore(flag)
                        , this.getScoreProductsByColumnId(VERY_SCORE_COLUMN_ID)));
        // 导航栏
        response.setActivityNavList(
                this.getActivityNavList("SCORE_TO_PRO"));
        // 品牌列表
        BrandExample brandExample = new BrandExample();
        brandExample.setOrderByClause("sort desc");
        brandExample.createCriteria().andStatusEqualTo(1);
        List<Brand> brandList = brandMapper.selectByExample(brandExample);
        response.setBrandList(brandList);

        // 假用户
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> usersFake = fakeUserList.stream()
                .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                .limit(20)
                .collect(Collectors.toList());
        response.setUsersFakes(usersFake);
        // 假用户数量
        response.setUsersNum(RandomUtil.getSectionNum(700, 1000));

        return response;
    }

    @Override
    public H5ScorePageResponse getH5ScoreListByTypeV2(Integer flag) {
        H5ScorePageResponse response = new H5ScorePageResponse();

        response.setCashScoreColumnMap(
                this.getCashScoreColumn(
                        this.getCashScoreProductsByScore(flag)));
        // 导航栏
        response.setActivityNavList(this.getActivityNavList("SCORE_TO_PRO"));

        return response;
    }

    private List<ProductShortResponse> getScoreProductsByColumnId(int columnId) {

        String redisKey = "scoreProductByColumnId:" + columnId;
        Set<Object> veryScoreProductsByRedis = redisService.sGet(redisKey);
        List<Product> veryScoreProducts = null;
        if (veryScoreProductsByRedis.isEmpty()) {
            veryScoreProducts=productDao.queryActivityProductList(ActivityTypeEnums.CASH_SCORE.name(),columnId,null,null,
                    null,TokenUtil.getPlatformData(),null,null,null,null);

            veryScoreProducts.stream().forEach(item -> {
                redisService.sSetAndTime(redisKey, 120, JSON.toJSONString(item));
            });
        } else {
            Iterator iterator = veryScoreProductsByRedis.iterator();
            veryScoreProducts = new LinkedList<>();
            while (iterator.hasNext()) {
                String productStr = (String) iterator.next();
                Product product = com.alibaba.fastjson.JSONObject.parseObject(productStr, Product.class);
                veryScoreProducts.add(product);
            }
        }
//                veryScoreProducts.addAll(freeProducts);
        return veryScoreProducts.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    private List<ProductShortResponse> getCashScoreByColumnIdWithShuffle(int columnId) {
        List<ProductShortResponse> getProductResponse = this.getScoreProductsByColumnId(columnId);
        Collections.shuffle(getProductResponse);
        return getProductResponse;
    }

    private List<ProductShortResponse> getChangeSeniority() {
        List<ProductShortResponse> changeProductResponse = this.getScoreProductsByColumnId(9);
        changeProductResponse = changeProductResponse.stream().limit(10).collect(Collectors.toList());
        int i = 1;
        for (ProductShortResponse productResponse : changeProductResponse) {
            productResponse.setSort(i++);
        }
        return changeProductResponse;
    }

    private List<ProductShortResponse> getCashScoreProductsByScore(Integer flag) {
        PageHelper.startPage(1, 40);
        ProductExample firstProductExample = new ProductExample();
        firstProductExample.setOrderByClause("sort desc");
        ProductExample.Criteria criteria = firstProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));

        String redisKey = "cashScoreProduct:score:";
        MinAndMEnums minAndMEnums = MinAndMEnums.getMinAndMax(flag);
        if (flag >= 1 && flag <= 2) {
            criteria.andActivityMaxBetween(new BigDecimal(minAndMEnums.getMin()), new BigDecimal(minAndMEnums.getMax()));
        } else if (flag == 3) {
            criteria.andActivityMaxGreaterThan(new BigDecimal(minAndMEnums.getMin()));
        }
        redisKey = "flag:" + flag;

        String realRedisKey = redisKey;
        Set<Object> firstProductsByRedis = redisService.sGet(redisKey);
        List<Product> firstProducts = null;
        if (firstProductsByRedis.isEmpty()) {
            firstProducts = Optional.ofNullable(productMapper.selectByExample(firstProductExample))
                    .orElse(new ArrayList<>());
            firstProducts.stream().forEach(item -> {
                redisService.sSetAndTime(realRedisKey, 120, JSON.toJSONString(item));
            });
        } else {
            Iterator iterator = firstProductsByRedis.iterator();
            firstProducts = new LinkedList<>();
            while (iterator.hasNext()) {
                String productStr = (String) iterator.next();
                Product product = com.alibaba.fastjson.JSONObject.parseObject(productStr, Product.class);
                firstProducts.add(product);
            }
        }

        List<ProductShortResponse> firstProductResponse = firstProducts.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
        // Collections.shuffle(firstProductResponse);

        return firstProductResponse;
    }

    /**
     * 根据不同积分活动栏目获取app积分产品列表 app, 不要返回全部和免费兑,新增一个精选栏目, 并且是把所有栏目的商品列表在一次性返回
     *
     * @return
     */
    @Override
    public ScorePageResponse getScoreListByType(UsersResponse user) {
        ScorePageResponse response = new ScorePageResponse();

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_APPCASH";
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            response = JSONObject.parseObject(s, ScorePageResponse.class);
        } else {
            response.setCashScoreColumn(this.getCashScoreList());
            // 品牌列表
            BrandExample brandExample = new BrandExample();
            brandExample.setOrderByClause("sort desc");
            brandExample.createCriteria().andStatusEqualTo(1);
            List<Brand> brandList = brandMapper.selectByExample(brandExample);
            response.setBrandList(brandList);
            // 假用户
            List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
            Collections.shuffle(fakeUserList);
            List<UsersFake> usersFake = fakeUserList.stream()
                    .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                    .limit(20)
                    .collect(Collectors.toList());
            response.setUsersFakes(usersFake);
            // 假用户数量
            response.setUsersNum(RandomUtil.getSectionNum(700, 1000));

            redisService.set(key, JSONObject.toJSONString(response));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        if (user == null) {
            response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
            response.setIsSign(0);// 前端要在app中没有用户登录的时候,签到也不要返回null,而要返回0
        } else {
            UsersDto usersDto = usersClient.getUsersInfo(user.getId());
            response.setScore(usersDto.getScore());
            response.setIsSign(usersClient.isSign(user.getId()));
        }
        response.setDefaultScore(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE));
        return response;
    }

    private Map<String, List<ProductShortResponse>> getCashScoreList() {
        Map<String, List<ProductShortResponse>> cashScoreColumn = new HashMap<>();

        // 查询全部积分商品
        List<ProductShortResponse> superChangeList = this.getCashScoreAll();
        Collections.shuffle(superChangeList);
        cashScoreColumn.put("SUPER_CHANGE", this.screenProductList(superChangeList));
        // 排行榜的数据
        List<ProductShortResponse> changeSeniorityList = this.getCashScores(9);
        cashScoreColumn.put("CHANGE_SENIORITY", this.screenProductList(changeSeniorityList));
        // 猜你喜欢
        List<ProductShortResponse> getLikeList = this.getCashScores(6);
        cashScoreColumn.put("GET_LIKE", this.screenProductList(getLikeList));
        // 品质好物
        List<ProductShortResponse> veryScoreList = this.getCashScores(6);
        cashScoreColumn.put("VERY_SCORE", this.screenProductList(veryScoreList));
        // 返积分商品
        List<ProductShortResponse> getScoreList = screenProductList(this.getReturnCashList(ActivityTypeEnums.GET_SCORE.name()));
        cashScoreColumn.put("GET_SCORE", getScoreList);

        List<ProductShortResponse> cashScoreZero = productDao.findCashScoreZero(TokenUtil.getPlatformData());
        cashScoreColumn.put("CASH_SCORE_ZERO", cashScoreZero);

        return cashScoreColumn;
    }

    private List<ProductShortResponse> getCashScoreAll() {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    private List<ProductShortResponse> getCashScores(Integer num) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        Collections.shuffle(products);
        if (num != null) {
            products = products.stream().limit(num).collect(Collectors.toList());
        }
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    /**
     *积分兑换排行（获取所有积分兑换排序前6个商品作为兑换排行）
     * @return
     */
    private List<ProductShortResponse> getChangeSeniorityList() {
        ProductExample allProductExample = new ProductExample();
        PageHelper.startPage(1, 6);
        allProductExample.setOrderByClause("sort desc");
        allProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));

        List<Product> scoreProducts = productMapper.selectByExample(allProductExample);
        return scoreProducts.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    private Map<String, List<ProductShortResponse>> getCashScoreColumn(List<ProductShortResponse> superProductResponse, List<ProductShortResponse> veryScoreProductResponse) {
        Map<String, List<ProductShortResponse>> cashScoreColumn = new HashMap<>();
        // 获取SUPER_CHANGE商品列表

        List<ProductShortResponse> superChangeList = screenProductList(superProductResponse);
        cashScoreColumn.put("SUPER_CHANGE", this.getCollectList(superChangeList, 6));


        if("tool".equals(TokenUtil.getSourcePlatform())){
            //兑换排行
            List<ProductShortResponse> changeProductResponse = this.getScoreProductsByColumnId(83);
            List<ProductShortResponse> changeSeniorityList = screenProductList(changeProductResponse);
            cashScoreColumn.put("CHANGE_SENIORITY", changeSeniorityList);
            // 获取GET_LIKE商品列表
            List<ProductShortResponse> getProductResponse = this.getCashScoreByColumnIdWithShuffle(84);
            List<ProductShortResponse> getLikeList = screenProductList(getProductResponse);
            cashScoreColumn.put("GET_LIKE", getLikeList);
        }else {
            // 获取CHANGE_SENIORITY兑换排行商品列表
            //List<ProductShortResponse> changeProductResponse = this.getChangeSeniority();
            List<ProductShortResponse> changeProductResponse = this.getChangeSeniorityList();
            List<ProductShortResponse> changeSeniorityList = screenProductList(changeProductResponse);
            cashScoreColumn.put("CHANGE_SENIORITY", changeSeniorityList);
            // 获取GET_LIKE商品列表
            List<ProductShortResponse> getProductResponse = this.getCashScoreByColumnIdWithShuffle(GET_LIKE_COLUMN_ID);
            List<ProductShortResponse> getLikeList = screenProductList(getProductResponse);
            cashScoreColumn.put("GET_LIKE", getLikeList);
        }

        // 获取VERY_SCORE商品列表
        List<ProductShortResponse> veryScoreList = screenProductList(veryScoreProductResponse);
        cashScoreColumn.put("VERY_SCORE", veryScoreList);

        // 免费兑商品
//        List<ProductShortResponse> freeExchangeList = getCashScoreByColumnIdWithShuffle(25);
        List<ProductShortResponse> freeExchangeList = getPriceEqualsToZero();
        cashScoreColumn.put("FREE_EXCHANGE", freeExchangeList);

        // 返积分商品
        List<ProductShortResponse> getScoreList = screenProductList(this.getReturnCashList(ActivityTypeEnums.GET_SCORE.name()));
        cashScoreColumn.put("GET_SCORE", getScoreList);
        return cashScoreColumn;
    }

    private Map<String, List<ProductShortResponse>> getCashScoreColumnForRemote(List<ProductShortResponse> superProductResponse, List<ProductShortResponse> veryScoreProductResponse) {
        Map<String, List<ProductShortResponse>> cashScoreColumn = new HashMap<>();
        // 获取SUPER_CHANGE商品列表

        List<ProductShortResponse> superChangeList = screenProductList(superProductResponse);
        cashScoreColumn.put("SUPER_CHANGE", this.getCollectList(superChangeList, 6));


        if("vippy".equals(TokenUtil.getSourcePlatform())){
            //兑换排行
            List<ProductShortResponse> changeProductResponse = this.getScoreProductsByColumnId(143);
            List<ProductShortResponse> changeSeniorityList = screenProductList(changeProductResponse);
            cashScoreColumn.put("CHANGE_SENIORITY", changeSeniorityList);
            // 获取GET_LIKE商品列表
            List<ProductShortResponse> getProductResponse = this.getCashScoreByColumnIdWithShuffle(144);
            List<ProductShortResponse> getLikeList = screenProductList(getProductResponse);
            cashScoreColumn.put("GET_LIKE", getLikeList);
        }else {
            // 获取CHANGE_SENIORITY兑换排行商品列表
            //List<ProductShortResponse> changeProductResponse = this.getChangeSeniority();
            List<ProductShortResponse> changeProductResponse = this.getChangeSeniorityList();
            List<ProductShortResponse> changeSeniorityList = screenProductList(changeProductResponse);
            cashScoreColumn.put("CHANGE_SENIORITY", changeSeniorityList);
            // 获取GET_LIKE商品列表
            List<ProductShortResponse> getProductResponse = this.getCashScoreByColumnIdWithShuffle(REMOTE_REGION_GET_LIKE);
            List<ProductShortResponse> getLikeList = screenProductList(getProductResponse);
            cashScoreColumn.put("GET_LIKE", getLikeList);
        }

        // 获取VERY_SCORE商品列表
        List<ProductShortResponse> veryScoreList = screenProductList(veryScoreProductResponse);
        cashScoreColumn.put("VERY_SCORE", veryScoreList);

        // 免费兑商品
//        List<ProductShortResponse> freeExchangeList = getCashScoreByColumnIdWithShuffle(25);
        List<ProductShortResponse> freeExchangeList = getPriceEqualsToZero();
        cashScoreColumn.put("FREE_EXCHANGE", freeExchangeList);

        // 返积分商品
        List<ProductShortResponse> getScoreList = screenProductList(this.getReturnCashList(ActivityTypeEnums.GET_SCORE.name()));
        cashScoreColumn.put("GET_SCORE", getScoreList);
        return cashScoreColumn;
    }

    private List<ProductShortResponse> getPriceEqualsToZero() {
        ProductExample allProductExample = new ProductExample();
        allProductExample.setOrderByClause("sort desc");
        allProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andPriceEqualTo(BigDecimal.valueOf(0))
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> veryScoreProducts = productMapper.selectByExample(allProductExample);
//                veryScoreProducts.addAll(freeProducts);
        List<ProductShortResponse> getProductResponse = veryScoreProducts.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());

        Collections.shuffle(getProductResponse);
        return getProductResponse;
    }

    private List<ProductShortResponse> screenProductList(List<ProductShortResponse> productList) {
        String freeProduct = sysConfigUtil.getSysConfig("FREE_PRODUCT");
        List<Integer> freeProductId = this.convertType(freeProduct);
        productList = productList.stream().sorted(Comparator.comparing(ProductShortResponse::getSort).reversed())
                .map(item -> {
                    if (freeProductId.contains(item.getId())) {
                        item.setIsFreeProduct(1);
                    } else {
                        item.setIsFreeProduct(0);
                    }
                    return item;
                }).collect(Collectors.toList());
        return productList;
    }

    private List<ProductResponse> freeProductList(List<ProductResponse> productList) {
        String freeProduct = sysConfigUtil.getSysConfig("FREE_PRODUCT");
        List<Integer> freeProductId = this.convertType(freeProduct);
        productList = productList.stream()
                .map(item -> {
                    if (freeProductId.contains(item.getId())) {
                        item.setIsFreeProduct(1);
                    } else {
                        item.setIsFreeProduct(0);
                    }
                    return item;
                }).collect(Collectors.toList());
        return productList;
    }

    /**
     * 进一步处理数据
     *
     * @return
     */
    private List<ProductShortResponse> getCollectList(List<ProductShortResponse> productList, Integer frontNum) {
        List<ProductShortResponse> list = new ArrayList<>();
        List<ProductShortResponse> frontList = productList.subList(0, frontNum);
        List<ProductShortResponse> afterList = productList.subList(frontNum, productList.size());
        Collections.shuffle(afterList);
        list.addAll(frontList);
        list.addAll(afterList);
        return list;
    }

    /**
     * 根据活动类型 、栏目 查询对应的商品列表
     *
     * @param activityType
     * @return
     */
    private List<ProductShortResponse> getReturnCashList(String activityType) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(activityType)
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo(ProductActivityStatusEnums.UP.getValue());
        List<Product> productList = productMapper.selectByExample(example);
        return productList.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    private Map<String, List<ProductShortResponse>> getCashScoreColumn(List<ProductShortResponse> superProductResponse) {
        Map<String, List<ProductShortResponse>> cashScoreColumn = new HashMap<>();
        // 获取SUPER_CHANGE商品列表
        cashScoreColumn.put("SUPER_CHANGE", superProductResponse);

//        // 获取CHANGE_SENIORITY商品列表
//        List<ProductResponse> changeProductResponse = this.getChangeSeniority();
//        cashScoreColumn.put("CHANGE_SENIORITY", changeProductResponse);
//
//        // 获取GET_LIKE商品列表
//        List<ProductResponse> getProductResponse = this.getCashScoreByColumnIdWithShuffle(GET_LIKE_COLUMN_ID);
//        cashScoreColumn.put("GET_LIKE", getProductResponse);
//
//        // 获取VERY_SCORE商品列表
//        cashScoreColumn.put("VERY_SCORE", veryScoreProductResponse);
        return cashScoreColumn;
    }

    /**
     * @param usersResponse
     * @Description :兑换中心页
     */
    @Override
    public ChangeCenterResponse getChangeCenterData(UsersResponse usersResponse) {
        ChangeCenterResponse changeCenterResponse = new ChangeCenterResponse();
        // 获取积分商品列表
        changeCenterResponse.setCashScoreProductList(this.getScoreByIds());

        // 查询该优惠券下所有的商品
        changeCenterResponse.setCashCouponList(this.getCashCoupon());

        // 查询0元测评
        // 查询该用户下是否在助力 && 正在助力的商品名称
        changeCenterResponse.setZeroEvaluationList(this.getEvaluationProductResponses(usersResponse));

        // 查询以旧换新
        changeCenterResponse.setOldProductList(this.getOldForNew());

        return changeCenterResponse;
    }

    @Override
    public List<ProductResponse> getLikeInRecharge() {
        ProductExample getLikeInRechargeExample = new ProductExample();
        getLikeInRechargeExample.createCriteria()
                .andIdIn(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.GET_LIKE_IN_RECHARGE)));
        List<Product> getLikeInRechargeProducts = productMapper.selectByExample(getLikeInRechargeExample);
        return getLikeInRechargeProducts.stream().map(ProductResponse::new).collect(Collectors.toList());
    }

    @Override
    public ScorePageResponse getScoreListByTypeV2(UsersResponse user, Integer flag) {
        ScorePageResponse response = new ScorePageResponse();

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_APPCASH_" + flag;
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            response = JSONObject.parseObject(s, ScorePageResponse.class);
        } else {
            response.setCashScoreColumn(
                    this.getCashScoreColumn(
                            this.getCashScoreProductsByScore(flag)));
            redisService.set(key, JSONObject.toJSONString(response));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        if (user == null) {
            response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
            response.setIsSign(0);// 前端要在app中没有用户登录的时候,签到也不要返回null,而要返回0
        } else {
            UsersDto usersDto = usersClient.getUsersInfo(user.getId());
            response.setScore(usersDto.getScore());
            response.setIsSign(usersClient.isSign(user.getId()));
        }
        response.setDefaultScore(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE));
        return response;
    }

    /**
     * 获取9.9秒杀的今日热抢和明日预告
     *
     * @return
     */
    @Override
    public NewKillResponse getNineSecKillColumn() {
        List<ProductResponse> todayProducts = new ArrayList<>();
        List<ProductResponse> tomorrowProducts = new ArrayList<>();
        // 今日热抢商品
        List<Product> nowAndTomorrowSecKillProducts = Optional.ofNullable(productDao.getNowAndTomorrowSecKillProducts(TokenUtil.getDataType(), TokenUtil.getPlatformData())).orElse(new ArrayList<>());
        if (!CollectionUtils.isEmpty(nowAndTomorrowSecKillProducts)) {
            todayProducts = nowAndTomorrowSecKillProducts.stream()
                    .filter(item -> this.isToday(item.getExtra()))
                    .map(item -> {
                        ProductResponse productResponse = new ProductResponse(item);
                        // 随机生成 库存进度码
//                        productResponse.setStockProgress(RandomUtil.getSectionNum(10,20));
                        try {
                            BigDecimal baseStock = new BigDecimal(Optional.ofNullable(productResponse.getStock()%17).orElse(0))
                                    .multiply(new BigDecimal(100))
                                    .divide(new BigDecimal(5678), 2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal stockProgress = new BigDecimal(1)
                                    .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                            if(stockProgress.intValue()>=100||stockProgress.intValue()<=0){
                                productResponse.setStockProgress(60);
                            }else {
                                productResponse.setStockProgress(stockProgress.intValue());
                            }
                        } catch (ApiException e) {
                            productResponse.setStockProgress(80);
                        }
                        return productResponse;
                    })
                    .collect(Collectors.toList());
            // 明日预告商品
            tomorrowProducts = nowAndTomorrowSecKillProducts.stream()
                    .filter(item -> this.isTomorrow(item.getExtra()))
                    .map(ProductResponse::new)
                    .collect(Collectors.toList());
        }
        // 广告推荐商品
        List<ProductResponse> advertList = Optional.ofNullable(productDao.getNewKillProductList(TokenUtil.getDataType(), TokenUtil.getPlatformData())).orElse(new ArrayList<>()).stream()
                .filter(item -> Optional.ofNullable(item.getIsAdvert()).orElse(0) == 1)
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        ;
        // 假用户
        List<UsersFake> fakeUserList = fakeUserUtil.getFakeUserList();

        NewKillResponse newKillResponse = new NewKillResponse();
        newKillResponse.setFakeUserList(fakeUserList);
        newKillResponse.setAdvertList(advertList);
        newKillResponse.setRankList(todayProducts);
        newKillResponse.setKillList(tomorrowProducts);
        return newKillResponse;
    }

    private boolean isTomorrow(String extra) {
        if (StringUtils.isNotEmpty(extra)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE, 1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String tomorrowStr = sdf.format(calendar.getTime());

            String[] firstExtra = extra.trim().split(" ");
            if (firstExtra != null && firstExtra.length > 0) {
                return tomorrowStr.equals(firstExtra[0]);
            }
        }
        return false;
    }

    private boolean isToday(String extra) {
        if (StringUtils.isNotEmpty(extra)) {
            String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

            String[] firstExtra = extra.trim().split(" ");
            if (firstExtra != null && firstExtra.length > 0) {
                return todayStr.equals(firstExtra[0]);
            }
        }

        return false;
    }

    /**
     * 优惠券列表v2,根据sort排序,获取前10个
     *
     * @return
     */
    @Override
    public UserCouponResponse getCouponListV2ByPage(Integer pageNum, Integer pageSize) {
        UserCouponResponse userCouponResponse = new UserCouponResponse();
        PageHelper.startPage(pageNum, pageSize);
        // 查询该优惠券下所有的商品
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()))
                .andIdIn(this.convertType(sysConfigUtil.getSysConfig("COUPON_IDS_BY_PAGE")))
        ;
        List<Product> products = productMapper.selectByExample(productExample);
        if (!CollectionUtils.isEmpty(products)) {
            List<ProductResponse> productResponses = products.stream().map(ProductResponse::new).collect(Collectors.toList());
            Collections.shuffle(productResponses);
            userCouponResponse.setCouponList(productResponses);
        }
        return userCouponResponse;
    }

    @Override
    public UserCouponResponseV2 getCouponListV3ByPage(Integer pageNum, Integer pageSize, Integer couponPrice) {
        CouponPriceEnums couponPriceEnums = CouponPriceEnums.getCouponPriceEnums(couponPrice);
        PageHelper.startPage(pageNum, pageSize);
        BigDecimal activityMax = null;
        if (couponPrice != null && couponPrice != 0) {
            activityMax = new BigDecimal(couponPriceEnums.getCouponPrice());
        }
        // 查询该优惠券下所有的商品
        List<ProductTinyResponse> productTinyResponse = productActivityDao.getCouponListByActivityMax(activityMax, TokenUtil.getPlatformData());
        // 查询用户红包
//        UsersResponse usersResponse = this.getUsersActivityMax();
        ReturnCouponResponse returnCouponResponse;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON + TokenUtil.getToken());
        } else {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid());
        }
        UserCouponResponseV2 userCouponResponse = new UserCouponResponseV2();
        userCouponResponse.setCouponList(productTinyResponse);
        userCouponResponse.setActivityMax(returnCouponResponse.getActivityMax());

        return userCouponResponse;
    }

    private UsersResponse getUsersActivityMax() {
        String token = TokenUtil.getToken();
//        if ("h5".equals(TokenUtil.getSource())) {
//            token = TokenUtil.getToken();
//        } else {
//            token = TokenUtil.getUuid();
//        }
        UsersResponse usersResponse = new UsersResponse();
        String s = redisService.get(token);
        if (StringUtils.isNotEmpty(s)) {
            usersResponse = JSONObject.parseObject(redisService.get(token), UsersResponse.class);
            usersResponse.setActivityMax(Optional.ofNullable(usersResponse.getActivityMax()).orElse(new BigDecimal(680)));
            redisService.set(token, JSON.toJSONString(usersResponse));
        }
        return usersResponse;
    }

    @Override
    public Map<String, Object> getWarmProducts() {
        Map<String, Object> result = new HashMap<>();
        List<SpecialMapResponse> specialList = new ArrayList<>();
        String key = "PICE_LEAK_PAGE";
        String warmproductListKey = "warmProductList";
        String recommendListKey = "recommendList";
        String special1Key = "special1";
        String special2Key = "special2";
        String special3Key = "special3";
        String special4Key = "special4";
        String special5Key = "special5";
        String special6Key = "special6";
        String special7Key = "special7";
        List<ProductTinyResponse> warmProductList;
        List<ProductTinyResponse> recommendList;
        List<ProductTinyResponse> special1;
        List<ProductTinyResponse> special2;
        List<ProductTinyResponse> special3;
        List<ProductTinyResponse> special4;
        List<ProductTinyResponse> special5;
        List<ProductTinyResponse> special6;
        List<ProductTinyResponse> special7;
        Map<Object, Object> piceLeakMap = redisService.getHashEntries(key);
        if (piceLeakMap.size() > 0) {
            if (piceLeakMap.get(warmproductListKey) == null) {
                warmProductList = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.WARM_PRODUCTS)));
                warmProductList.stream()
                        .map(item -> {
                            BankerSite bankerSite = bankerSiteDao.queryBankerSiteByBankerId(item.getBankerId());
                            item.setBankerLogo(bankerSite.getLogo());
                            return item;
                        }).collect(Collectors.toList());
            } else {
                warmProductList = JSONArray.parseArray(piceLeakMap.get(warmproductListKey).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(recommendListKey) == null) {
                recommendList = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.WARM_PRODUCTS_2)));
            } else {
                recommendList = JSONArray.parseArray(piceLeakMap.get(recommendListKey).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special1Key) == null) {
                special1 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_1")));
            } else {
                special1 = JSONArray.parseArray(piceLeakMap.get(special1Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special2Key) == null) {
                special2 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_2")));
            } else {
                special2 = JSONArray.parseArray(piceLeakMap.get(special2Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special3Key) == null) {
                special3 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_3")));
            } else {
                special3 = JSONArray.parseArray(piceLeakMap.get(special3Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special4Key) == null) {
                special4 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_4")));
            } else {
                special4 = JSONArray.parseArray(piceLeakMap.get(special4Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special5Key) == null) {
                special5 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_5")));
            } else {
                special5 = JSONArray.parseArray(piceLeakMap.get(special5Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special6Key) == null) {
                special6 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_6")));
            } else {
                special6 = JSONArray.parseArray(piceLeakMap.get(special6Key).toString(), ProductTinyResponse.class);
            }
            if (piceLeakMap.get(special7Key) == null) {
                special7 = productDao
                        .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_7")));
            } else {
                special7 = JSONArray.parseArray(piceLeakMap.get(special7Key).toString(), ProductTinyResponse.class);
            }
        } else {
            warmProductList = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.WARM_PRODUCTS)));
            warmProductList.stream()
                    .map(item -> {
                        BankerSite bankerSite = bankerSiteDao.queryBankerSiteByBankerId(item.getBankerId());
                        item.setBankerLogo(bankerSite.getLogo());
                        return item;
                    }).collect(Collectors.toList());
            recommendList = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig(SysConfigConstants.WARM_PRODUCTS_2)));
            special1 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_1")));
            special2 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_2")));
            special3 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_3")));
            special4 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_4")));
            special5 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_5")));
            special6 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_6")));
            special7 = productDao
                    .queryProductTinyByIds(this.convertType(sysConfigUtil.getSysConfig("SPECIAL_PRODUCTS_7")));
            redisService.add(key, warmproductListKey, JSON.toJSONString(warmProductList));
            redisService.add(key, recommendListKey, JSON.toJSONString(recommendList));
            redisService.add(key, special1Key, JSON.toJSONString(special1));
            redisService.add(key, special2Key, JSON.toJSONString(special2));
            redisService.add(key, special3Key, JSON.toJSONString(special3));
            redisService.add(key, special4Key, JSON.toJSONString(special4));
            redisService.add(key, special5Key, JSON.toJSONString(special5));
            redisService.add(key, special6Key, JSON.toJSONString(special6));
            redisService.add(key, special7Key, JSON.toJSONString(special7));
            redisService.expire(key, ExpireTimeConstant.PICE_LEAK_PAGE_TIME);
        }
        SpecialMapResponse specialList1 = new SpecialMapResponse();
        specialList1.setName("服饰女装");
        specialList1.setProductList(special1);
        specialList.add(specialList1);

        SpecialMapResponse specialList2 = new SpecialMapResponse();
        specialList2.setName("美妆个护");
        specialList2.setProductList(special2);
        specialList.add(specialList2);

        SpecialMapResponse specialList3 = new SpecialMapResponse();
        specialList3.setName("家电厨具");
        specialList3.setProductList(special3);
        specialList.add(specialList3);

        SpecialMapResponse specialList4 = new SpecialMapResponse();
        specialList4.setName("家居家纺");
        specialList4.setProductList(special4);
        specialList.add(specialList4);

        SpecialMapResponse specialList5 = new SpecialMapResponse();
        specialList5.setName("首饰手表");
        specialList5.setProductList(special5);
        specialList.add(specialList5);

        SpecialMapResponse specialList6 = new SpecialMapResponse();
        specialList6.setName("居家百货");
        specialList6.setProductList(special6);
        specialList.add(specialList6);

        SpecialMapResponse specialList7 = new SpecialMapResponse();
        specialList7.setName("美食饮品");
        specialList7.setProductList(special7);
        specialList.add(specialList7);

        result.put(warmproductListKey, warmProductList);
        result.put(recommendListKey, recommendList);
        result.put("snapNum", RandomUtil.getSectionNum(6000, 8000));
        result.put("specialList", specialList);

        return result;
    }

    @Override
    public WarmProductResponse getWarmProductsV2(Integer productId) {
        // 热门单品
        ProductTinyResponse warmProduct = productActivityDao.getHotProductById(productId, TokenUtil.getPlatformData(), TokenUtil.getDataType());
        Optional.ofNullable(warmProduct)
                .orElseThrow(() -> new ApiException(ResultCode.NO_ADVERT));
        // 查询单品banner
//        ProductImgExample example = new ProductImgExample();
//        example.setOrderByClause("sort asc,id asc");
//        example.createCriteria()
//                .andProductIdEqualTo(productId)
//                .andTypeEqualTo("banner");
//        List<ProductImg> productImgList = productImgMapper.selectByExample(example);
//        warmProduct.setBannerList(productImgList);
        Integer hotProductId = warmProduct.getHotProductId();
        List<HotProductBanner> hotProductBanners = productActivityDao.getHotProductBanner(hotProductId, TokenUtil.getPlatformData());
        warmProduct.setHotProductBanners(hotProductBanners);
        warmProduct.setActivityMax(warmProduct.getOriginalPrice().subtract(warmProduct.getPrice()).setScale(2, BigDecimal.ROUND_UP));
        // 推荐商品列表
        List<ProductTinyResponse> recommendList = productActivityDao.getHotProductRecommend(hotProductId, TokenUtil.getPlatformData(), TokenUtil.getDataType());
        // 从抄底捡漏开始
        // 每个单品对应的分类列表
        List<HotProductCategory> hotProductCategories = productActivityDao.getCategoryList(hotProductId);
        List<SpecialMapResponse> specialMapResponses = hotProductCategories.stream()
                .map(item -> {
                    List<ProductTinyResponse> hotCategoryProducts = productActivityDao.getHotCategoryProduct(item.getId(), TokenUtil.getPlatformData(), TokenUtil.getDataType());
                    SpecialMapResponse specialList = new SpecialMapResponse();
                    specialList.setProductList(hotCategoryProducts);
                    specialList.setName(item.getName());
                    return specialList;
                })
                .collect(Collectors.toList());

        WarmProductResponse warmProductResponse = new WarmProductResponse();
        warmProductResponse.setWarmProduct(warmProduct);
        warmProductResponse.setRecommendList(recommendList);
        warmProductResponse.setSpecialList(specialMapResponses);
        warmProductResponse.setSnapNum(RandomUtil.getSectionNum(6000, 8000));
        return warmProductResponse;
    }

    @Override
    public OldForNewExtResponse queryOldForNewColumn(Integer productId) {
        String token = TokenUtil.getToken();
        String subsidyKey = RedisConstants.SUBSIDYKEY;

        OldForNewExtResponse result = new OldForNewExtResponse();
        ActivityColumnExample example = new ActivityColumnExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andIdIn(Arrays.asList(14, 34, 35, 36))
                .andStatusEqualTo((byte) 1)
                .andTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name());
        List<ActivityColumn> activityColumnList = activityColumnMapper.selectByExample(example);
        List<ExtResponse> columnList = activityColumnList.stream()
                .map(item -> {
                    ExtResponse extResponse = new ExtResponse();
                    extResponse.setId(item.getId());
                    extResponse.setExtra(item.getExtra());
                    extResponse.setTitle(item.getTitle());
                    return extResponse;
                })
                .collect(Collectors.toList());
        result.setColumnList(columnList);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCount(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));

        if (productId != null) {
            Product product = productDao.getProductById(productId);
            OldForNewProductDto extensionData = new OldForNewProductDto(product);
//            this.isReceiveSubsidy(productId, extensionData);
            result.setExtensionData(extensionData);
        }
        // 获取用户的领取信息
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);

        PageHelper.startPage(1, 20);
        ProductExample productExample = new ProductExample();
        productExample.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusEqualTo((byte) 1);
        List<Product> productList = productMapper.selectByExample(productExample);
        PageHelper.clearPage();
        List<UsersFake> usersFake = fakeUserUtil.getFakeUserList();
        List<UserFakeResponse> userFakeResponse = new ArrayList<>();
        for (int i = 0; i < productList.size(); i++) {
            // 用户列表 跟 商品列表都是取20个  由于用户列表一定会有20条数据 但商品不一定有20条数据 此处需要循环商品列表数据
            UsersFake item = usersFake.get(i);
            Product product = productList.get(i);
            BigDecimal activityMax = product.getActivityMax();
            BigDecimal originalPrice = product.getOriginalPrice();
            int receivePrice = RandomUtil.getSectionNum(activityMax.intValue(), originalPrice.intValue());
            BigDecimal money = new BigDecimal(receivePrice);
            BigDecimal pay = originalPrice.subtract(money);
            item.setMoney(pay.setScale(2, BigDecimal.ROUND_UP));
            UserFakeResponse data = new UserFakeResponse(item);
            data.setProductId(product.getId());
            data.setProductImg(product.getProductImg());
            data.setProductName(product.getProductName());
            // 领取了多少元
            data.setTotalMoney(money);
            // 花了多少元购买
            data.setMoney(pay.setScale(2, BigDecimal.ROUND_UP));
            Object subsidyData = subsidyHash.get(product.getId().toString());
            if (null == subsidyData) {
                data.setIsReceiveSubsidy(0);
            } else {
                data.setIsReceiveSubsidy(1);
            }
            userFakeResponse.add(data);
        }
        result.setNum(RandomUtil.getSectionNum(5000, 8000));
        result.setFakeUserList(userFakeResponse);
        return result;
    }

    @Override
    public OldForNewExtResponse queryOldForNewColumnApp(Integer productId) {
        String token = TokenUtil.getUuid();
        String subsidyKey = RedisConstants.SUBSIDYKEY_APP;

        OldForNewExtResponse result = new OldForNewExtResponse();
        ActivityColumnExample example = new ActivityColumnExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andIdIn(Arrays.asList(14, 34, 35, 36))
                .andStatusEqualTo((byte) 1)
                .andTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name());
        List<ActivityColumn> activityColumnList = activityColumnMapper.selectByExample(example);
        List<ExtResponse> columnList = activityColumnList.stream()
                .map(item -> {
                    ExtResponse extResponse = new ExtResponse();
                    extResponse.setId(item.getId());
                    extResponse.setExtra(item.getExtra());
                    extResponse.setTitle(item.getTitle());
                    return extResponse;
                })
                .collect(Collectors.toList());
        result.setColumnList(columnList);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCount(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));

        if (productId != null) {
            Product product = productDao.getProductById(productId);
            OldForNewProductDto extensionData = new OldForNewProductDto(product);
//            this.isReceiveSubsidy(productId, extensionData);
            result.setExtensionData(extensionData);
        }
        // 获取用户的领取信息
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);

        PageHelper.startPage(1, 20);
        ProductExample productExample = new ProductExample();
        productExample.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusEqualTo((byte) 1);
        List<Product> productList = productMapper.selectByExample(productExample);
        PageHelper.clearPage();
        List<UsersFake> usersFake = fakeUserUtil.getFakeUserList();
        List<UserFakeResponse> userFakeResponse = new ArrayList<>();
        for (int i = 0; i < productList.size(); i++) {
            // 用户列表 跟 商品列表都是取20个  由于用户列表一定会有20条数据 但商品不一定有20条数据 此处需要循环商品列表数据
            UsersFake item = usersFake.get(i);
            Product product = productList.get(i);
            BigDecimal activityMax = product.getActivityMax();
            BigDecimal originalPrice = product.getOriginalPrice();
            int receivePrice = RandomUtil.getSectionNum(activityMax.intValue(), originalPrice.intValue());
            BigDecimal money = new BigDecimal(receivePrice);
            BigDecimal pay = originalPrice.subtract(money);
            item.setMoney(pay.setScale(2, BigDecimal.ROUND_UP));
            UserFakeResponse data = new UserFakeResponse(item);
            data.setProductId(product.getId());
            data.setProductImg(product.getProductImg());
            data.setProductName(product.getProductName());
            // 领取了多少元
            data.setTotalMoney(money);
            // 花了多少元购买
            data.setMoney(pay.setScale(2, BigDecimal.ROUND_UP));
            Object subsidyData = subsidyHash.get(product.getId().toString());
            if (null == subsidyData) {
                data.setIsReceiveSubsidy(0);
            } else {
                data.setIsReceiveSubsidy(1);
            }
            userFakeResponse.add(data);
        }
        result.setNum(RandomUtil.getSectionNum(5000, 8000));
        result.setFakeUserList(userFakeResponse);
        return result;
    }

    private void isReceiveSubsidy(Integer productId, OldForNewProductDto extensionData) {
        String subsidyKey = RedisConstants.SUBSIDYKEY;
        String token = TokenUtil.getToken();
        extensionData.setIsReceiveSubsidy(0);
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (subsidyHash != null && subsidyHash.size() > 0) {
            Object subsidyData = subsidyHash.get(productId.toString());
            if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                extensionData.setIsReceiveSubsidy(1);
            }
        }
    }

    @Override
    public List<OldForNewProductDto> queryOldForNewList(Integer columnId) {
        ProductExample example = new ProductExample();
        List<Product> productList;
        if (columnId == 14) {
            // 查询所有以旧换新商品
            example.setOrderByClause("sort desc");
            example.createCriteria()
                    .andActivityTypeEqualTo("OLD_FOR_NEW")
                    .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                    .andStatusEqualTo(((byte) 1));
            productList = productMapper.selectByExample(example);
        } else {
            // 根据栏目查询对应商品
            example.setOrderByClause("sort desc");
            example.createCriteria()
                    .andColumnIdEqualTo(columnId)
                    .andActivityTypeEqualTo("OLD_FOR_NEW")
                    .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                    .andStatusEqualTo(((byte) 1));
            productList = productMapper.selectByExample(example);
        }
        List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
        Integer count = 14;
        List<Product> resultList = new ArrayList<>();
        List<OldForNewProductDto> oldForNewProductList;
        if (productList.size() > count) {
            List<Product> frontList = productList.subList(0, count);
            List<Product> afterList = productList.subList(count, productList.size());
            Collections.shuffle(afterList);
            resultList.addAll(frontList);
            resultList.addAll(afterList);
            oldForNewProductList = resultList.stream()
                    .map(item -> {
                        OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                        Collections.shuffle(fakeUserList);
                        List<String> imgs = fakeUserList.stream()
                                .limit(4)
                                .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                                .filter(user -> null != user && null != user.getHeadImg())
                                .map(UsersFake::getHeadImg)
                                .collect(Collectors.toList());
                        oldForNewProductDto.setUsersFake(imgs);
                        oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                        return oldForNewProductDto;
                    })
                    .collect(Collectors.toList());
        } else {
            oldForNewProductList = productList.stream()
                    .map(item -> {
                        OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                        Collections.shuffle(fakeUserList);
                        List<String> imgs = fakeUserList.stream()
                                .limit(4)
                                .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                                .filter(user -> null != user && null != user.getHeadImg())
                                .map(UsersFake::getHeadImg)
                                .collect(Collectors.toList());
                        oldForNewProductDto.setUsersFake(imgs);
                        oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                        return oldForNewProductDto;
                    })
                    .collect(Collectors.toList());
        }
        return oldForNewProductList;
    }

    @Override
    public List<ProductResponse> getProductsByBrandType(Integer pageNum, Integer pageSize, String activityType) {
        PageHelper.startPage(pageNum, pageSize);
        ProductExample oldForNewProductExample = new ProductExample();
        oldForNewProductExample.setOrderByClause("sort desc");
        oldForNewProductExample.createCriteria()
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andActivityTypeEqualTo(activityType)
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> productList = productMapper.selectByExample(oldForNewProductExample);
        List<ProductResponse> productResponses = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productList)) {
            productResponses = productList.stream()
                    .map(ProductResponse::new)
                    .collect(Collectors.toList());
        }
        List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
        String subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
        String token = TokenUtil.getToken();
        if (ActivityTypeEnums.OLD_FOR_NEW.name().equals(activityType)) {
            productResponses = productResponses.stream()
                    .map(i -> {
                        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
                        i.setIsReceiveSubsidy(0);
                        if (subsidyHash != null) {
                            Object subsidyData = subsidyHash.get(i.getId().toString());
                            if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                                i.setIsReceiveSubsidy(1);
                            }
                        }
                        Collections.shuffle(fakeUserList);
                        List<String> imgs = fakeUserList.stream()
                                .limit(4)
                                .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                                .filter(user -> null != user && null != user.getHeadImg())
                                .map(UsersFake::getHeadImg)
                                .collect(Collectors.toList());
                        i.setUsersFake(imgs);
                        i.setNum(RandomUtil.getSectionNum(700, 1200));
                        return i;
                    })
                    .collect(Collectors.toList());
        }

        return productResponses;
    }


    private List<ProductResponse> getOldForNew() {
        ProductExample oldForNewProductExample = new ProductExample();
        oldForNewProductExample.setOrderByClause("sort desc");
        oldForNewProductExample.createCriteria()
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> productList = productMapper.selectByExample(oldForNewProductExample);
        List<ProductResponse> oldProductList = productList.stream()
                .map(ProductResponse::new)
                .limit(4)
                .collect(Collectors.toList());
        oldProductList.stream().forEach(product -> {
            BigDecimal originalPrice = product.getOriginalPrice();
            BigDecimal price = product.getPrice();
            product.setSubsidy(originalPrice.subtract(price).setScale(2, BigDecimal.ROUND_UP));
        });
        return oldProductList;
    }

    private List<EvaluationProductResponse> getEvaluationProductResponses(UsersResponse usersResponse) {
        Map<String, Object> helpInfoMap = new HashMap<>();
        helpInfoMap.put("status", 0);
        if (usersResponse != null && usersResponse.getId() != null) {
            HelpWork helpWork = evaluationProductDao.getHelpWorkInfoByUserId(usersResponse.getId());
            if (helpWork != null) {
                String productText = helpWork.getProductName();
                // 正在助力
                helpInfoMap.put("status", 1);
                // 商品名称
                helpInfoMap.put("productText", productText);
            }
        }
        PageHelper.startPage(0, 3);
        List<Product> evaluationProducts = evaluationProductDao.findZeroProduct(1);
        return evaluationProducts.stream()
                .map(item -> {
                    EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(item);
                    BankerSiteInfoResponse bankerSiteInfoResponse = bankerSiteDao.queryBankerSiteOne(evaluationProductResponse.getBankerId());
                    if (bankerSiteInfoResponse != null) {
                        evaluationProductResponse.setTitle(BankerNameEnums.getName(bankerSiteInfoResponse.getBankerType(), bankerSiteInfoResponse.getTitle()));
                    }
                    // 是否助力&&助力商品名称
                    evaluationProductResponse.setHelpInfoMap(helpInfoMap);
                    // 0元测评用stock_evaluation代替stock
                    evaluationProductResponse.setStock(item.getStockEvaluation());
                    return evaluationProductResponse;
                })
                .collect(Collectors.toList());
    }

    private List<ProductResponse> getCashCoupon() {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_COUPON.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> products = productMapper.selectByExample(productExample);
        return products.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);
                    try {
                        BigDecimal baseStock = new BigDecimal(Optional.ofNullable(productResponse.getStock()%17).orElse(0))
                                .multiply(new BigDecimal(100))
                                .divide(new BigDecimal(5678), 2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal stockProgress = new BigDecimal(1)
                                .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                        if(stockProgress.intValue()>=100||stockProgress.intValue()<=0){
                            productResponse.setStockProgress(60);
                        }else {
                            productResponse.setStockProgress(stockProgress.intValue());
                        }
                    } catch (ApiException e) {
                        productResponse.setStockProgress(80);
                    }
                    int i = RandomUtil.getSectionNum(1, 3);
                    switch (i) {
                        case 1:
                            productResponse.setTips("限时限量");
                            break;
                        case 2:
                            productResponse.setTips("7天无理由退换");
                            break;
                        case 3:
                            productResponse.setTips("顺丰包邮");
                            break;
                    }
                    return productResponse;
                })
                .collect(Collectors.toList());
    }

    private List<ProductResponse> getScoreByIds() {
        ProductExample superProductExample = new ProductExample();
        superProductExample.setOrderByClause("sort desc");
        superProductExample.createCriteria()
                .andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue(),
                        ProductActivityStatusEnums.PRESELL.getValue()));
        List<Product> cashScoreProducts = productMapper.selectByExample(superProductExample);
        List<ProductResponse> cashScoreProductList = cashScoreProducts.stream()
                .map(ProductResponse::new)
                .limit(10)
                .collect(Collectors.toList());
//        Collections.shuffle(cashScoreProductList);
        return cashScoreProductList;
    }

    private List<UsersFake> getFakeUserList() {
        // 从redis中获取假用户数据
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        return fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .limit(10)
                .collect(Collectors.toList());
    }

    @Override
    public List<ActivityProductResponse> getActivityList(Integer pageNum, Integer pageSize, String activityType, BigDecimal activityMax, String productName) {
        PageHelper.startPage(pageNum, pageSize);
        String platformData = TokenUtil.getPlatformData();
        List<ActivityProductResponse> activityProductResponseList=productDao.findActivityList(activityType, activityMax, productName,platformData);
        Collections.shuffle(activityProductResponseList);

        activityProductResponseList.stream().forEach(item ->{
            item.setPrice(item.getPrice().setScale(0,BigDecimal.ROUND_DOWN));
            item.setOriginalPrice(item.getOriginalPrice().setScale(0,BigDecimal.ROUND_DOWN));
            String headImgStr = redisService.get(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId());
            if (StringUtils.isNotBlank(headImgStr)) {
                List<String> list = JSONObject.parseArray(headImgStr, String.class);
                item.setHeadImgs(list);
            } else {
//                List<Integer> userIds = ordersDao.selectByProductId(item.getId());
//                List<String> headImgs = usersInfoMapper.selectHeadImgsByUserId(userIds);
                List<String> headImgs = usersInfoMapper.selectHeadImgs();
                String s = JSONObject.toJSONString(headImgs);
                redisService.set(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId(), s);
                redisService.expire(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId(), 60 * 60);
                item.setHeadImgs(headImgs);
            }


            BigDecimal discount=new BigDecimal(1);
            if(item.getOriginalPrice().compareTo(BigDecimal.ZERO)>0) {
                discount = (item.getPrice().divide(item.getOriginalPrice(),2).multiply(new BigDecimal(10))).setScale(1);
            }
            if(discount.compareTo(BigDecimal.ZERO)==0){
                discount=new BigDecimal(1);
            }
            if(discount.compareTo(new BigDecimal(discount.intValue()))==0){
                item.setDiscount(String.valueOf(discount.intValue()));
            }else {
                item.setDiscount(String.valueOf(discount));
            }
            if (null != item.getPrice()) {
                item.setPrice(new BigDecimal(item.getPrice().stripTrailingZeros().toPlainString()));
            }
            if (null != item.getOriginalPrice()) {
                item.setOriginalPrice(new BigDecimal(item.getOriginalPrice().stripTrailingZeros().toPlainString()));
            }
            //商品标签
            List<ActivityProductLabel> labels = productDao.findProductLabel(item.getId());
            item.setLabels(labels);
        });
        return activityProductResponseList;
    }

    @Override
    public List<ActivityProductResponse> getActivityListFixPrice(Integer pageNum, Integer pageSize, String activityType, BigDecimal activityMax, String productName) {
        PageHelper.startPage(pageNum, pageSize);
        String platformData = TokenUtil.getPlatformData();
        BigDecimal fixPrice = new BigDecimal(fixPriceParam);
        List<ActivityProductResponse> activityProductResponseList=productDao.findActivityListFixPrice(activityType, activityMax, productName,platformData, fixPrice);
        Collections.shuffle(activityProductResponseList);
        activityProductResponseList.stream().forEach(item ->{
            BigDecimal discount=new BigDecimal(1);
            if(item.getOriginalPrice().compareTo(BigDecimal.ZERO)>0) {
                discount = (item.getPrice().divide(item.getOriginalPrice(),2).multiply(new BigDecimal(10))).setScale(1);
            }
            if(discount.compareTo(BigDecimal.ZERO)==0){
                discount=new BigDecimal(1);
            }
            if(discount.compareTo(new BigDecimal(discount.intValue()))==0){
                item.setDiscount(String.valueOf(discount.intValue()));
            }else {
                item.setDiscount(String.valueOf(discount));
            }
            if (null != item.getPrice()) {
                item.setPrice(new BigDecimal(item.getPrice().stripTrailingZeros().toPlainString()));
            }
            if (null != item.getOriginalPrice()) {
                item.setOriginalPrice(new BigDecimal(item.getOriginalPrice().stripTrailingZeros().toPlainString()));
            }
        });
        return activityProductResponseList;
    }

    @Override
    public List<ActivityProductResponse> getActivityListByRange(Integer pageNum, Integer pageSize, String activityType, BigDecimal activityMaxStart, BigDecimal activityMaxEnd) {
        PageHelper.startPage(pageNum, pageSize);
        String platformData = TokenUtil.getPlatformData();
        List<ActivityProductResponse> activityProductResponseList=productDao.findActivityListByRange(activityType, activityMaxStart,activityMaxEnd,platformData);
        Collections.shuffle(activityProductResponseList);
        activityProductResponseList.stream().forEach(item ->{
            BigDecimal discount=new BigDecimal(1);
            if(item.getOriginalPrice().compareTo(BigDecimal.ZERO)>0) {
                discount = (item.getPrice().divide(item.getOriginalPrice(),2).multiply(new BigDecimal(10))).setScale(1);
            }
            if(discount.compareTo(BigDecimal.ZERO)==0){
                discount=new BigDecimal(1);
            }
            if(discount.compareTo(new BigDecimal(discount.intValue()))==0){
                item.setDiscount(String.valueOf(discount.intValue()));
            }else {
                item.setDiscount(String.valueOf(discount));
            }
        });
        return activityProductResponseList;
    }


    @Override
    public OldForNewReceiveResponse getNotReceiveList(Integer pageNum, Integer pageSize) {
        OldForNewReceiveResponse response = new OldForNewReceiveResponse();

        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getNotReceivedProducts(pageNum, pageSize);

        Collections.shuffle(productResponses);
        response.setProductList(productResponses);
        response.setUsersFake(this.getFakeUserList());
        return response;
    }

    @Override
    public OldForNewReceiveResponse getNotReceiveListV2(Integer pageNum, Integer pageSize) {
        OldForNewReceiveResponse response = new OldForNewReceiveResponse();

        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getNotReceivedProductsV2(RedisConstants.SUBSIDYKEY, pageNum, pageSize);
        response.setProductList(productResponses);
        response.setUsersFake(this.getFakeUserList());
        return response;
    }

    private List<OldForNewProductDto> getNotReceivedProducts(Integer pageNum, Integer pageSize) {
        List<OldForNewProductDto> productResponses = new ArrayList<>();
        String token;
        String subsidyKey;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            subsidyKey = RedisConstants.SUBSIDYKEY;
            token = TokenUtil.getToken();
        } else {
            subsidyKey = RedisConstants.SUBSIDYKEY_APP;
            token = TokenUtil.getUuid();
        }
        List<Product> products;
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (null != subsidyHash && subsidyHash.size() > 0) {
            List<Integer> productIds = subsidyHash.keySet().stream()
                    .map(item -> Integer.valueOf(item.toString())).collect(Collectors.toList());

            PageHelper.startPage(pageNum, pageSize);
            ProductExample productExample = new ProductExample();
            productExample.setOrderByClause("sort desc");
            productExample.createCriteria()
                    .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                    .andStatusEqualTo((byte) 1)
                    .andIdNotIn(productIds);
            products = productMapper.selectByExample(productExample);
        } else {
            PageHelper.startPage(pageNum, pageSize);
            ProductExample productExample = new ProductExample();
            productExample.setOrderByClause("sort desc");
            productExample.createCriteria()
                    .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                    .andStatusEqualTo((byte) 1);
            products = productMapper.selectByExample(productExample);
        }

        if (!CollectionUtils.isEmpty(products)) {
            List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
            productResponses = products.stream().map(item -> {
                OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                Collections.shuffle(fakeUserList);
                List<String> imgs = fakeUserList.stream()
                        .limit(4)
                        .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                        .filter(user -> null != user && null != user.getHeadImg())
                        .map(UsersFake::getHeadImg)
                        .collect(Collectors.toList());
                oldForNewProductDto.setUsersFake(imgs);
                oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                return oldForNewProductDto;
            }).collect(Collectors.toList());

        }
        return productResponses;
    }

    private List<OldForNewProductDto> getNotReceivedProductsV2(String subsidyKey, Integer pageNum, Integer pageSize) {
        List<OldForNewProductDto> productResponses = new ArrayList<>();
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        List<Product> products;

        PageHelper.startPage(pageNum, pageSize);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusEqualTo((byte) 1);
        products = productMapper.selectByExample(productExample);

        if (!CollectionUtils.isEmpty(products)) {
            List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
            productResponses = products.stream().map(item -> {
                OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                Collections.shuffle(fakeUserList);
                List<String> imgs = fakeUserList.stream()
                        .limit(4)
                        .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                        .filter(user -> null != user && null != user.getHeadImg())
                        .map(UsersFake::getHeadImg)
                        .collect(Collectors.toList());
                oldForNewProductDto.setUsersFake(imgs);
                oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                return oldForNewProductDto;
            }).collect(Collectors.toList());

        }
        return productResponses;
    }

    @Override
    public OldForNewExtResponse getOldForNewProductsOfH5User(Integer flag, Integer columnId, BigDecimal activityMax) {
        OldForNewExtResponse result = new OldForNewExtResponse();

        // 触发领取前面10个商品
        //  this.addTenOldProducts2User(RedisConstants.SUBSIDYKEY, RedisConstants.RECORD_SUBSIDYKEY);

        // Product product = productMapper.selectByPrimaryKey(2598);

        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getReceivedProducts(RedisConstants.SUBSIDYKEY);
//        OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(product);
//        oldForNewProductDto.setIsReceiveSubsidy(1);
//        productResponses.add(2, oldForNewProductDto);
        result.setReceivedProducts(productResponses);

        // 获取用户补贴领取情况
        RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubsidyInfo(RedisConstants.RECORD_SUBSIDYKEY);
        log.info("token={},recordSubsidyDataDto={}", TokenUtil.getToken(),recordSubsidyDataDto.toString());
        BigDecimal totalReceive = recordSubsidyDataDto.getReceived();
        BigDecimal used = recordSubsidyDataDto.getUsed();
        BigDecimal notUsed = totalReceive.compareTo(used) > 0
                ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP)
                : BigDecimal.ZERO;

        result.setTotalReceive(totalReceive);
        result.setUsed(used);
        result.setNotUsed(notUsed);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));

        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCountAndActivityMax(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData(), activityMax);
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));

        // 假用户
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UserFakeResponse> usersList = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .limit(10)
                .map(UserFakeResponse::new)
                .collect(Collectors.toList());
        result.setFakeUserList(usersList);

        List<OldForNewProductDto> rankProductList =this.queryOldForNewList(15,1,10,flag, activityMax);
        rankProductList = rankProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        result.setRankingList(rankProductList);
        List<OldForNewProductDto> oldForNewProductList = this.queryOldForNewList(37,1,20,flag, activityMax);
        oldForNewProductList = oldForNewProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        Collections.shuffle(oldForNewProductList);
        result.setRecommendList(oldForNewProductList);
        //换新专享
        List<OldForNewProductDto> oldForNewVIPProductList = this.queryOldForNewList(53,1,20,flag, activityMax);
        oldForNewVIPProductList = oldForNewVIPProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        result.setVipList(oldForNewVIPProductList);

        return result;
    }


    private RecordSubsidyDataDto insertRecordSubsidy(BigDecimal activityMax, String recordSubsidykey, String token) {
        String recordKey = recordSubsidykey + token;
        RecordSubsidyDataDto recordSubsidyDataDto = new RecordSubsidyDataDto();

        String recordSubsidyData = redisService.get(recordKey);
        if (StringUtils.isNotEmpty(recordSubsidyData)) {
            recordSubsidyDataDto = com.alibaba.fastjson.JSONObject.parseObject(recordSubsidyData, RecordSubsidyDataDto.class);
        }

        recordSubsidyDataDto.setToken(Optional.ofNullable(recordSubsidyDataDto.getToken())
                .orElse(token));
        recordSubsidyDataDto.setReceived(Optional.ofNullable(recordSubsidyDataDto.getReceived())
                .orElse(BigDecimal.ZERO)
                .add(activityMax).setScale(2, BigDecimal.ROUND_HALF_UP));
        recordSubsidyDataDto.setReceiveTime(Optional.ofNullable(recordSubsidyDataDto.getReceiveTime())
                .orElse(new Date()));

        redisService.set(recordKey, JSON.toJSONString(recordSubsidyDataDto));
        redisService.expire(recordKey, ExpireTimeConstant.SUBSIDY_DATA_TIME);

        return recordSubsidyDataDto;
    }

    private RecordSubsidyDataDto getTotalReceive(String token, String recordSubsidykeyApp) {
        RecordSubsidyDataDto recordSubsidyDataDto = new RecordSubsidyDataDto();

        String recordKey = recordSubsidykeyApp + token;
        String recordSubsidyData = redisService.get(recordKey);
        if (StringUtils.isNotEmpty(recordSubsidyData)) {
            recordSubsidyDataDto = com.alibaba.fastjson.JSONObject.parseObject(recordSubsidyData, RecordSubsidyDataDto.class);
        }

        recordSubsidyDataDto.setUsed(Optional.ofNullable(recordSubsidyDataDto.getUsed()).orElse(BigDecimal.ZERO));
        recordSubsidyDataDto.setReceived(Optional.ofNullable(recordSubsidyDataDto.getReceived()).orElse(BigDecimal.ZERO));
        recordSubsidyDataDto.setToken(Optional.ofNullable(recordSubsidyDataDto.getToken()).orElse(token));
        recordSubsidyDataDto.setReceiveTime(Optional.ofNullable(recordSubsidyDataDto.getReceiveTime()).orElse(new Date()));

        return recordSubsidyDataDto;

    }

    @Override
    public OldForNewExtResponse getOldForNewProductsOfAppUser() {
        OldForNewExtResponse result = new OldForNewExtResponse();

//        // 触发领取前面10个商品
//        this.addTenOldProducts2User(RedisConstants.SUBSIDYKEY_APP, RedisConstants.RECORD_SUBSIDYKEY_APP);


        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getReceivedProducts(RedisConstants.SUBSIDYKEY_APP);
        List<OldForNewProductDto> receivedProducts = new ArrayList<>();
        List<OldForNewProductDto> receivedExpireProducts = new ArrayList<>();
        BigDecimal totalReceive = BigDecimal.ZERO;
        for(OldForNewProductDto oldForNewProductDto:productResponses){
            if(oldForNewProductDto.getTime()!=null&&oldForNewProductDto.getTime().getTime()<System.currentTimeMillis()){//已过期
                receivedExpireProducts.add(oldForNewProductDto);
            }else{
                receivedProducts.add(oldForNewProductDto);
                totalReceive = totalReceive.add(oldForNewProductDto.getActivityMax());
            }
        }
        result.setReceivedProducts(receivedProducts);
        result.setReceivedExpireProducts(receivedExpireProducts);

        // 获取用户补贴领取情况
        RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubsidyInfo(RedisConstants.RECORD_SUBSIDYKEY_APP);

//        BigDecimal totalReceive = recordSubsidyDataDto.getReceived();
        BigDecimal used = recordSubsidyDataDto.getUsed();
//        BigDecimal notUsed = totalReceive.compareTo(used) > 0 ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP) : BigDecimal.ZERO;

        result.setTotalReceive(totalReceive);
        result.setUsed(used);
//        result.setNotUsed(notUsed);
        result.setNotUsed(totalReceive);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));

        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCount(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));

        return result;
    }

    private void addTenOldProducts2User(String subsidyKey, String recordKeyApp) {

        // 取出10个以旧换新商品
        PageHelper.startPage(1, 10);
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        ProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDataTypeEqualTo(TokenUtil.getDataType())
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> productList = productMapper.selectByExample(productExample);
        PageHelper.clearPage();

        // 将10个商品赋给用户
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);

        productList.stream().forEach(item -> {
            Object subsidyData = subsidyHash.get(item.getId().toString());

            if (null == subsidyData) {
                SubsidyDataDto subsidyDataDto = new SubsidyDataDto();
                subsidyDataDto.setToken(token);
                subsidyDataDto.setProductId(item.getId());
                subsidyDataDto.setActivityMax(item.getActivityMax());
                subsidyDataDto.setReceiveTime(new Date());
                redisService.add(subsidyKey + token, item.getId().toString(), JSON.toJSONString(subsidyDataDto));
                redisService.expire(subsidyKey + token, ExpireTimeConstant.SUBSIDY_DATA_TIME);

                this.insertRecordSubsidy(item.getActivityMax(), recordKeyApp, token);
            }
        });
    }

    @Override
    public ActivityH5Response getActivityListH5() {
        ActivityH5Response activityH5Response = new ActivityH5Response();
        // 假用户
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> usersFakes = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .filter(item -> StringUtils.isNotEmpty(item.getProductName()))
                .filter(user -> null != user && null != user.getHeadImg())
                .limit(Integer.parseInt(sysConfigUtil.getSysConfig("ACTIVITY_LIST_USER_NUM")))
                .collect(Collectors.toList());
        activityH5Response.setUsersFakes(usersFakes);

        // 红包商品列表
        activityH5Response.setCashCouponList(this.getActivityProduct(ActivityTypeEnums.CASH_COUPON.name(), 27));
        // 积分商品列表
        List<ProductResponse> cashScore = this.freeProductList(this.getActivityProduct(ActivityTypeEnums.CASH_SCORE.name(), 30));
        activityH5Response.setCashScoreList(cashScore);
        // 补贴商品列表
        List<ProductResponse> activityProduct = this.getActivityProduct(ActivityTypeEnums.OLD_FOR_NEW.name(), 30);
        activityH5Response.setOldForNewList(activityProduct);
        List<ProductResponse> responseList = this.getActivityProduct(ActivityTypeEnums.RECHARGE_COUPON.name(), 100);
        Collections.shuffle(responseList);
        //话费商品
        activityH5Response.setRechargeCouponList(responseList);
        return activityH5Response;
    }

    /**
     * 该用户是否领取该商品
     *
     * @param productId
     * @return
     */
    private Boolean isReceive(Integer productId) {
        String subsidyKey;
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equalsIgnoreCase(TokenUtil.getSource())) {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
            token = TokenUtil.getToken();
        } else {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP;
            token = TokenUtil.getUuid();
        }
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (subsidyHash != null && subsidyHash.size() > 0) {
            Object subsidyData = subsidyHash.get(productId.toString());
            if (null != subsidyData && StringUtils.isNotEmpty((String) subsidyData)) {
                return true;
            }
        }
        return false;
    }

    private List<Integer> getSubsidyProductIds() {
        String subsidyKey;
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
            token = TokenUtil.getToken();
        } else {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP;
            token = TokenUtil.getUuid();
        }
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);

        if(subsidyHash != null && subsidyHash.size() > 0){
            List<Integer> list = subsidyHash.keySet().stream().map(e -> Integer.parseInt(e.toString())).collect(Collectors.toList());
            return list;
        }
        return null;
    }

    @Override
    public BigDecimal getSubsidyAmount() {
        String subsidyKey;
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY;
            token = TokenUtil.getToken();
        } else {
            subsidyKey = com.ytjj.qmyx.mall.constants.RedisConstants.SUBSIDYKEY_APP;
            token = TokenUtil.getUuid();
        }
        BigDecimal amount = BigDecimal.ZERO;
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (subsidyHash != null && subsidyHash.size() > 0) {
            for(Object value : subsidyHash.values()){
                try {
                    SubsidyDataDto subsidyDataDto = JSONObject.parseObject(value.toString(), SubsidyDataDto.class);
                    amount = amount.add(subsidyDataDto.getActivityMax());
                }catch (Exception e) {}
            }
        }
        return amount;
    }

    @Override
    public ActivityAppResponse getActivityListApp() {
        ActivityAppResponse activityAppResponse = new ActivityAppResponse();
        // 假用户
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> usersFakes = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .filter(user -> null != user && null != user.getHeadImg() && null != user.getProductName())
                .limit(Integer.parseInt(sysConfigUtil.getSysConfig("ACTIVITY_LIST_USER_NUM")))
                .collect(Collectors.toList());
        activityAppResponse.setUsersFakes(usersFakes);
        // 红包商品列表
        activityAppResponse.setCashCouponList(this.getActivityProduct(ActivityTypeEnums.CASH_COUPON.name(), 27));
        // 积分商品列表
        List<ProductResponse> cashScore = this.freeProductList(this.getActivityProduct(ActivityTypeEnums.CASH_SCORE.name(), 30));
        activityAppResponse.setCashScoreList(cashScore);
        // 补贴商品列表
        activityAppResponse.setOldForNewList(this.getActivityProduct(ActivityTypeEnums.OLD_FOR_NEW.name(), 30));
        //话费商品
        activityAppResponse.setRechargeCouponList(this.getActivityProduct(ActivityTypeEnums.RECHARGE_COUPON.name(), 20));
        return activityAppResponse;
    }

    @Override
    public NewYearGoodsResponse getNewYearGoods(Integer type) {
        NewYearGoodsResponse response = new NewYearGoodsResponse();
        switch (type) {
            case 1:
                String newYearGoods1 = sysConfigUtil.getSysConfig("NEW_YEAR_GOODS_1");
                response.setProductList(productDao.queryNewYearGoods(this.convertType(newYearGoods1))
                        .stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList()));
                break;
            case 2:
                String newYearGoods2 = sysConfigUtil.getSysConfig("NEW_YEAR_GOODS_2");
                response.setProductList(productDao.queryNewYearGoods(this.convertType(newYearGoods2))
                        .stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList()));
                break;
            case 3:
                String newYearGoods3 = sysConfigUtil.getSysConfig("NEW_YEAR_GOODS_3");
                response.setProductList(productDao.queryNewYearGoods(this.convertType(newYearGoods3))
                        .stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList()));
                break;
            case 4:
                String newYearGoods4 = sysConfigUtil.getSysConfig("NEW_YEAR_GOODS_4");
                response.setProductList(productDao.queryNewYearGoods(this.convertType(newYearGoods4))
                        .stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList()));
                break;
            case 5:
                String newYearGoods5 = sysConfigUtil.getSysConfig("NEW_YEAR_GOODS_5");
                response.setProductList(productDao.queryNewYearGoods(this.convertType(newYearGoods5))
                        .stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList()));
                break;
            default:
                response = null;
        }
        return response;
    }

    @Override
    public Map<String, Object> getReturnCouponSpecial(UsersResponse h5CurrentUser) {
        // 获取假用户列表
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<UsersFake> usersFakes = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .filter(user -> null != user && null != user.getHeadImg())
                .limit(10)
                .collect(Collectors.toList());
        // 返现红包商品
        List<ProductResponse> returnCoupon = Optional.ofNullable(productActivityDao.getReturnCoupon(TokenUtil.getPlatformData())).orElse(new ArrayList<>());
        // 每个返现红包商品加上一个评论
        List<ProductReviews> productReviews = productReviewsMapper.selectByExample(new ProductReviewsExample());
        returnCoupon.stream().forEach(i -> {
            Collections.shuffle(productReviews);
            List<ProductReviewsResponse> productReviewsResponse = productReviews.stream()
                    .filter(item -> null != item && null != item.getContent() && null != item.getContent())
                    .limit(1)
                    .map(ProductReviewsResponse::new).collect(Collectors.toList());
            i.setProductReviewsResponses(productReviewsResponse);
        });
        // 用户红包
        ReturnCouponResponse returnCouponResponse;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON + TokenUtil.getToken());
        } else {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid());
        }
        h5CurrentUser.setActivityMax(returnCouponResponse.getActivityMax());

        HashMap<String, Object> result = new HashMap<>();
        result.put("returnCoupon", returnCoupon);
        result.put("fakeUserList", usersFakes);
        result.put("receivedNum", RandomUtil.getSectionNum(100_000, 1_000_000));
        result.put("h5CurrentUser", h5CurrentUser);
        return result;
    }

    @Override
    public UserCouponResponseV2 getCouponListV4ByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        BigDecimal activityMax = null;

        // 查询该优惠券下所有的商品
        List<ProductTinyResponse> productTinyResponse = Optional.ofNullable(productActivityDao.getCouponListByActivityMax(activityMax, TokenUtil.getPlatformData())).orElse(new ArrayList<>());

        // 查询用户红包
//        UsersResponse usersResponse = this.getUsersActivityMax();

        // 查询用户累计返现和用户已使用红包
        ReturnCouponResponse returnCouponResponse;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON + TokenUtil.getToken());
        } else {
            returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid());
        }


        UserCouponResponseV2 userCouponResponse = new UserCouponResponseV2();
        userCouponResponse.setCouponList(productTinyResponse);
        userCouponResponse.setActivityMax(returnCouponResponse.getActivityMax());
        userCouponResponse.setTotalReturnCoupon(returnCouponResponse.getTotalReturnCoupon());
        userCouponResponse.setUsedActivityMax(returnCouponResponse.getUsedActivityMax());

        return userCouponResponse;
    }

    @Override
    public Map<String, Object> signCoupon(UsersResponse h5CurrentUser) {
        String token = h5CurrentUser.getToken();
        String key = com.ytjj.common.constants.RedisConstants.H5_SIGN + "coupon:" + token;

        ReturnCouponResponse returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON + token);

        // 签到
        String signStr = redisService.get(key);
        if (StringUtils.isEmpty(signStr)) {
            // 标记用户已签到，并在第二天的凌晨过期
            redisService.set(key, token);
            redisService.expire(key, DateUtils.getCurTimeDiff());
            // 更新用户红包, 用户红包 + 签到红包
            Integer defaultCoupon = Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_COUPON));
            returnCouponResponse.setActivityMax(
                    returnCouponResponse.getActivityMax()
                            .add(BigDecimal.valueOf(defaultCoupon))
                            .setScale(0, BigDecimal.ROUND_UP));
            redisService.set(RedisConstants.RETURN_COUPON + token, com.alibaba.fastjson.JSON.toJSONString(returnCouponResponse));
        }

        HashMap<String, Object> data = new HashMap<>();
        data.put("isSign", 1);
        data.put("h5CurrentUser", returnCouponResponse);
        return data;

    }

    @Override
    public Map<String, Object> signCouponApp(UsersResponse h5CurrentUser) {
        String token = TokenUtil.getUuid();
        String key = com.ytjj.common.constants.RedisConstants.APP_SIGN + "coupon:" + token;
        ReturnCouponResponse returnCouponResponse = this.getReturnCoupon(RedisConstants.RETURN_COUPON_APP + token);

        // 签到
        String signStr = redisService.get(key);
        if (StringUtils.isEmpty(signStr)) {
            // 标记用户已签到，并在第二天的凌晨过期
            redisService.set(key, token);
            redisService.expire(key, DateUtils.getCurTimeDiff());
            // 更新用户红包, 用户红包 + 签到红包
            Integer defaultCoupon = Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_COUPON));
            returnCouponResponse.setActivityMax(
                    returnCouponResponse.getActivityMax()
                            .add(BigDecimal.valueOf(defaultCoupon))
                            .setScale(0, BigDecimal.ROUND_UP));
            redisService.set(
                    RedisConstants.RETURN_COUPON_APP + TokenUtil.getUuid()
                    , com.alibaba.fastjson.JSON.toJSONString(returnCouponResponse));

        }

        HashMap<String, Object> data = new HashMap<>();
        data.put("isSign", 1);
        data.put("h5CurrentUser", returnCouponResponse);
        return data;
    }

    @Override
    public Map<String, Object> getBrandsAndUsersHeadImg() {
        Map<String, Object> data = new HashMap<>();

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + "_BRAND_USER_" + TokenUtil.getDataType() + "_APPCASH";
        String s = redisService.get(key);
        if (StringUtils.isNotEmpty(s)) {
            data = JSONObject.parseObject(s, Map.class);
        } else {
            // 品牌列表
            BrandExample brandExample = new BrandExample();
            brandExample.setOrderByClause("sort desc");
            brandExample.createCriteria().andStatusEqualTo(1);
            List<Brand> brandList = brandMapper.selectByExample(brandExample);
            // 只返回品牌id和封面图
            List<Map<String, Object>> brandIds = brandList.stream().map(brand -> {
                Map<String, Object> brandMap = new HashMap<>();
                brandMap.put("id", brand.getId());
                brandMap.put("icon", brand.getIcon());
                return brandMap;
            }).collect(Collectors.toList());
            data.put("brandList", brandIds);
            // 假用户
            List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
            Collections.shuffle(fakeUserList);
            List<String> userHeadImgs = fakeUserList.stream()
                    .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                    .limit(20)
                    .filter(user -> null != user && null != user.getHeadImg())
                    .map(UsersFake::getHeadImg)
                    .collect(Collectors.toList());
            data.put("userHeadImgs", userHeadImgs);
            // 假用户数量
            data.put("usersNum", RandomUtil.getSectionNum(700, 1000));

            redisService.set(key, JSONObject.toJSONString(data));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }
        return data;
    }

    @Override
    public OldForNewExtResponse getOldForNewOrders() {
        OldForNewExtResponse result = new OldForNewExtResponse();
        List<OldForNewProductDto> productResponses = this.getOldForNewOrdersProductList();

        result.setReceivedProducts(productResponses);

        // 获取用户补贴领取情况
        RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubsidyInfo(RedisConstants.RECORD_SUBSIDYKEY);

        BigDecimal totalReceive = recordSubsidyDataDto.getReceived();
        BigDecimal used = recordSubsidyDataDto.getUsed();
        BigDecimal notUsed = totalReceive.compareTo(used) > 0
                ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP)
                : BigDecimal.ZERO;

        result.setTotalReceive(totalReceive);
        result.setUsed(used);
        result.setNotUsed(notUsed);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));

        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCount(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));

        return result;
    }

    public List<OldForNewProductDto> getOldForNewOrdersProductList() {
        List<OldForNewProductDto> products = ordersDao.queryOldForNewOrdersProductList(TokenUtil.getToken());
        if (!CollectionUtils.isEmpty(products)) {
            List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
            products = products.stream().map(item -> {
                Collections.shuffle(fakeUserList);

                List<String> imgs = fakeUserList.stream()
                        .limit(4)
                        .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                        .filter(user -> null != user && null != user.getHeadImg())
                        .map(UsersFake::getHeadImg)
                        .collect(Collectors.toList());

                item.setUsersFake(imgs);
                item.setIsReceiveSubsidy(1);
                item.setNum(RandomUtil.getSectionNum(700, 1200));
                return item;
            }).collect(Collectors.toList());

        }
        return products;
    }

    @Override
    public BrandScoreResponse getProductsByBrandId(Integer brandId) {
        Brand brand = brandMapper.selectByPrimaryKey(brandId);
        BrandScoreResponse result = new BrandScoreResponse();
        ProductExample example = new ProductExample();
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andBrandIdEqualTo(brandId)
                .andStatusEqualTo((byte) 1);
        List<Product> producs = productMapper.selectByExample(example);
        List<ProductResponse> productList = producs.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        // 免费兑积分商品
        List<ProductResponse> freeProductList = this.freeProductList(productList);
        result.setProductList(freeProductList);
        result.setBrandName(brand.getBrandName());
        result.setBrandTitle(brand.getBrandTitle());
        result.setCoverImg(brand.getCoverImg());
        result.setExtra(brand.getExtra());
        return result;
    }

    private ReturnCouponResponse getReturnCoupon(String key) {
        ReturnCouponResponse returnCouponResponse = new ReturnCouponResponse();

        String cs = redisService.get(key);
        if (StringUtils.isNotEmpty(cs)) {// 记录用户返现红包金额
            returnCouponResponse = JSONObject.parseObject(cs, ReturnCouponResponse.class);
        }

        returnCouponResponse.setUsedActivityMax(Optional.ofNullable(returnCouponResponse.getUsedActivityMax())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setTotalReturnCoupon(Optional.ofNullable(returnCouponResponse.getTotalReturnCoupon())
                .orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        returnCouponResponse.setActivityMax(Optional.ofNullable(returnCouponResponse.getActivityMax())
                .orElse(new BigDecimal(680)).setScale(0, BigDecimal.ROUND_HALF_UP));

        return returnCouponResponse;
    }

    /**
     * 根据活动类型查询对应的商品列表
     *
     * @param type
     * @return
     */
    private List<ProductResponse> getActivityProduct(String type, Integer num) {
        PageHelper.startPage(0, num);
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andActivityTypeEqualTo(type)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> productList = productMapper.selectByExample(example);
        return productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
    }

    private List<OldForNewProductDto> getReceivedProducts(String subsidyKey) {
        List<OldForNewProductDto> productResponses = new ArrayList<>();
        String token;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
        } else {
            token = TokenUtil.getUuid();
        }
        Map<Object, Object> subsidyHash = redisService.getHashEntries(subsidyKey + token);
        if (null != subsidyHash && subsidyHash.size() > 0) {
            List<SubsidyDataDto> datas = new ArrayList<>();
            for (Map.Entry entry : subsidyHash.entrySet()) {
                Object v = entry.getValue();
                SubsidyDataDto data = JSONObject.parseObject((String) v, SubsidyDataDto.class);
                datas.add(data);
            }
            List<Integer> productIds = datas.stream()
                    .sorted(Comparator.comparing(SubsidyDataDto::getReceiveTime).reversed())
                    .map(item -> item.getProductId())
                    .collect(Collectors.toList());
            List<Product> products = productDao.queryNewYearGoods(productIds);
            if (!CollectionUtils.isEmpty(products)) {
                List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());

                productResponses = products.stream().map(item -> {
                    OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                    Collections.shuffle(fakeUserList);

                    List<String> imgs = fakeUserList.stream()
                            .limit(4)
                            .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                            .filter(user -> null != user && null != user.getHeadImg())
                            .map(UsersFake::getHeadImg)
                            .collect(Collectors.toList());

                    oldForNewProductDto.setUsersFake(imgs);
                    oldForNewProductDto.setIsReceiveSubsidy(1);
                    oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                    SubsidyDataDto subsidyDataDto = datas.stream().filter(data -> data.getProductId().equals(item.getId())).findAny().orElse(null);
                    Date time = subsidyDataDto == null ? null : new Date(subsidyDataDto.getReceiveTime().getTime() + (1000*60*60*24L));
                    oldForNewProductDto.setTime(time);
                    return oldForNewProductDto;
                }).collect(Collectors.toList());

            }
        }
        return productResponses;
    }

    @Override
    public RecordSubsidyDataDto getUserSubsidyInfo(String recordSubsidyKey) {
        RecordSubsidyDataDto recordSubsidyDataDto = new RecordSubsidyDataDto();

        String token;
        String subsidykey=RedisConstants.SUBSIDYKEY_APP;
        if ("h5".equals(TokenUtil.getSource())||"quick-app".equals(TokenUtil.getSource())) {
            token = TokenUtil.getToken();
            subsidykey=RedisConstants.SUBSIDYKEY;
        } else {
            token = TokenUtil.getUuid();
            subsidykey=RedisConstants.SUBSIDYKEY_APP;
        }

        String recordKey = recordSubsidyKey + token;
        String recordDto = redisService.get(recordKey);
        if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(recordDto)) {
            recordSubsidyDataDto = JSONObject.parseObject(recordDto, RecordSubsidyDataDto.class);
        }

        recordSubsidyDataDto.setReceived(Optional.ofNullable(recordSubsidyDataDto.getReceived()).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        recordSubsidyDataDto.setUsed(Optional.ofNullable(recordSubsidyDataDto.getUsed()).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));
        recordSubsidyDataDto.setToken(Optional.ofNullable(recordSubsidyDataDto.getToken()).orElse(token));
        recordSubsidyDataDto.setReceiveTime(Optional.ofNullable(recordSubsidyDataDto.getReceiveTime()).orElse(new Date()));

        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getReceivedProducts(subsidykey);
        BigDecimal totalReceive = BigDecimal.ZERO;
        for(OldForNewProductDto oldForNewProductDto:productResponses){
            if(oldForNewProductDto.getTime()!=null&&oldForNewProductDto.getTime().getTime()<System.currentTimeMillis()){//已过期
            }else{
                totalReceive = totalReceive.add(oldForNewProductDto.getActivityMax());
            }
        }
        recordSubsidyDataDto.setReceived(totalReceive);

        return recordSubsidyDataDto;
    }

    /**
     * 根据活动类型查询对应的商品列表
     *
     * @param type
     * @return
     */
    @Override
    public List<OldForNewProductDto> getProductsByBrandType(String type) {

        ProductExample productExample = new ProductExample();
        productExample.createCriteria()
                .andIdIn(this.convertType(sysConfigUtil.getSysConfig(type)))
                .andStatusEqualTo(ProductStatusEnums.UP.getValue())
                .andPlatformDataIn(Arrays.asList("all", TokenUtil.getPlatformData()));
        List<Product> productList = productDao.queryNewYearGoods(this.convertType(sysConfigUtil.getSysConfig(type)));

        return productList.stream()
                .filter(product -> "OLD_FOR_NEW".equals(product.getActivityType()))
                .map(product -> {
                    OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(product);

                    if (isReceive(product.getId())) {
                        oldForNewProductDto.setIsReceiveSubsidy(1);
                    } else {
                        oldForNewProductDto.setIsReceiveSubsidy(0);
                    }

                    return oldForNewProductDto;
                }).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getBrandList() {
        Map<String, Object> data = new HashMap<>();
        List<String> types_v1 = Arrays.asList(sysConfigUtil.getSysConfig("BRAND_SUBSIDY").split(","));

        for (String type_v1 : types_v1) {

            ProductExample productExample = new ProductExample();
            productExample.createCriteria()
                    .andIdIn(this.convertType(sysConfigUtil.getSysConfig(type_v1)))
                    .andStatusEqualTo(ProductStatusEnums.UP.getValue())
                    .andPlatformDataIn(Arrays.asList("all", TokenUtil.getPlatformData()));
//            List<Product> productList = productMapper.selectByExample(productExample);
            List<Product> productList = productDao.queryNewYearGoods(this.convertType(sysConfigUtil.getSysConfig(type_v1)));

            List<OldForNewProductDto> products = productList.stream()
                    .filter(product -> "OLD_FOR_NEW".equals(product.getActivityType()))
                    .map(product -> {
                        OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(product);

                        if (isReceive(product.getId())) {
                            oldForNewProductDto.setIsReceiveSubsidy(1);
                        } else {
                            oldForNewProductDto.setIsReceiveSubsidy(0);
                        }

                        return oldForNewProductDto;
                    })
                    .collect(Collectors.toList());

            data.put(type_v1, products);
        }
        return data;
    }

    @Override
    public Map<String, Object> getHotProductDownload(Integer productId) {
        // 单品
        Product product = productMapper.selectByPrimaryKey(productId);
        ProductShortResponse hotProduct = new ProductShortResponse(product);

        // 补贴商品列表
        int limitNum = 29;
        List<ProductShortResponse> subsidyProducts = new ArrayList<>();
        subsidyProducts.add(hotProduct);

        List<ProductShortResponse> productShortResponseList = productActivityDao.getActivityProducts(productId,
                ActivityTypeEnums.OLD_FOR_NEW.name(),
                TokenUtil.getPlatformData(),
                limitNum);

        subsidyProducts.addAll(productShortResponseList);



        // 假用户头像
        List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
        Collections.shuffle(fakeUserList);
        List<String> userHeadImg = fakeUserList.stream()
                .limit(8)
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .filter(user -> null != user && null != user.getHeadImg())
                .map(UsersFake::getHeadImg)
                .collect(Collectors.toList());

        // 假用户数量
        int fakeUserNum = RandomUtil.getSectionNum(3000, 5000);

        Map<String, Object> data = new HashMap<>();
        data.put("hotProduct", hotProduct);
        data.put("subsidyProducts", subsidyProducts);
        data.put("userHeadImg", userHeadImg);
        data.put("fakeUserNum", fakeUserNum);
        return data;
    }

    @Override
    public Map<String, Object> queryCashScoreColumnH5() {
        Map<String, Object> result = new HashMap<>();

        String activityColumnKey = RedisConstants.ACTIVITY_COLUMN + ActivityTypeEnums.CASH_SCORE.name();
        Set<Object> activityColumns = redisService.sGet(activityColumnKey);
        if (activityColumns.isEmpty()) {
            // 栏目列表
            ActivityColumnExample example = new ActivityColumnExample();
            example.createCriteria()
                    .andStatusEqualTo((byte) 1)
                    .andTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name());
            List<ActivityColumn> columnList = activityColumnMapper.selectByExample(example);

            columnList.stream().forEach(item -> {
                redisService.sSetAndTime(activityColumnKey, 300, JSON.toJSONString(item));
            });
            result.put("columnList", columnList);
        }else {
            Iterator iterator = activityColumns.iterator();
            List<ActivityColumn> activityColumnList = new LinkedList<>();
            while (iterator.hasNext()) {
                String activityColumnStr = (String) iterator.next();
                ActivityColumn productImg = com.alibaba.fastjson.JSONObject.parseObject(activityColumnStr, ActivityColumn.class);
                activityColumnList.add(productImg);
            }
            result.put("columnList", activityColumnList);
        }

        // 假用户
        List<UsersFake> fakeUserList = getFakeUserList();
        result.put("fakeUserList", fakeUserList);
        return result;
    }

    @Override
    public List<ProductShortResponse> queryCashScoreListH5(Integer columnId, Integer pageSize, Integer pageNum,Integer flag,String consumerPower, Integer unionFlag) {
        PageHelper.startPage(pageNum, pageSize);
        BigDecimal activityMin=null;
        if (columnId != 55) {//低价专区忽略消费能力
            //人群消费能力,取值HIGN,LOW
            if ("HIGN".equalsIgnoreCase(consumerPower) || "LOW".equalsIgnoreCase(consumerPower)) {
                consumerPower=consumerPower.toUpperCase();
            }else{
                consumerPower=null;
            }
        }
        if (columnId == null || columnId == 0) {
            if(flag != null && flag == 1){
                activityMin=new BigDecimal(12000);
            }
        }
        List<Product> products = productDao.queryActivityProductList(ActivityTypeEnums.CASH_SCORE.name(),columnId,null,null,activityMin,TokenUtil.getPlatformData(),consumerPower,
                null,null,null);

        List<ProductShortResponse> productList = products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
        products = null;
        //columnId为0或8时分组打乱，前10条一组，后面一组
        if ((columnId == null || columnId == 0 || columnId == 8) && pageNum ==1) {
            if(flag != null && flag == 2 ){
                Collections.shuffle(productList);
            }else {
                if (productList.size() > 20) {
                    List<ProductShortResponse> top10ProductList = productList.subList(0, 20);
                    List<ProductShortResponse> lastProductList = productList.subList(20, productList.size());
                    Collections.shuffle(top10ProductList);
                    Collections.shuffle(lastProductList);
                    productList = new ArrayList<>();
                    productList.addAll(top10ProductList);
                    productList.addAll(lastProductList);
                    top10ProductList = null;
                    lastProductList = null;
                } else {
                    Collections.shuffle(productList);
                }
            }
        }else {
            Collections.shuffle(productList);
        }
        return productList;
    }

    @Override
    public List<ProductResponse> getCashScoreProductList(Integer pageSize, Integer pageNum) {
        String platformData = TokenUtil.getPlatformData();
        PageHelper.startPage(pageNum, pageSize);
        List<ProductResponse> cashScoreProducts = productDao.getCashScoreProducts(platformData);
        Collections.shuffle(cashScoreProducts);
        return cashScoreProducts;
    }

    @Override
    public List<OldForNewProductDto> queryOldForNewList(Integer columnId, Integer pageNum, Integer pageSize,Integer flag) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.queryActivityProductList("OLD_FOR_NEW",columnId,null,null,null,TokenUtil.getPlatformData(),
                null,null,null,null);
        if(columnId!=15) {//除榜单外随机打乱
            Collections.shuffle(productList);
        }
        List<OldForNewProductDto> oldForNewProductList = productList.stream()
                .map(item -> {
                    OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                    return oldForNewProductDto;
                })
                .collect(Collectors.toList());
//        }
        return oldForNewProductList;
    }

    @Override
    public List<OldForNewProductDto> queryOldForNewList(Integer columnId, Integer pageNum, Integer pageSize,Integer flag, BigDecimal activityMax) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.queryActivityProductList("OLD_FOR_NEW",columnId,activityMax,activityMax,null,TokenUtil.getPlatformData(),null,null,null,null);

        if(columnId!=15) {//除榜单外随机打乱
            Collections.shuffle(productList);
        }
        List<OldForNewProductDto> oldForNewProductList = productList.stream()
                .map(item -> {
                    OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                    return oldForNewProductDto;
                })
                .collect(Collectors.toList());
//        }
        return oldForNewProductList;
    }

    /**
     * 获取补贴商品列表
     * @param columnId
     * @param pageNum
     * @param pageSize
     * @param activityMin
     * @param activityMax
     * @param sort
     * @return
     */
    @Override
    public List<OldForNewProductDto> queryOldForNewList(Integer columnId, Integer pageNum, Integer pageSize,BigDecimal activityMin, BigDecimal activityMax,Integer sort) {
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = new ArrayList<>();

        if(1==columnId){//栏目id传1代表获取换新专区几个栏目商品
            List columnIdList=new ArrayList();
            columnIdList.add(41);
            columnIdList.add(42);
            columnIdList.add(43);
            columnIdList.add(44);
            columnIdList.add(45);
            productList = productDao.queryActivityProductList("OLD_FOR_NEW",null,activityMin,activityMax,null,TokenUtil.getPlatformData(),null,columnIdList,null,null);
        }else if(2==columnId){//栏目id传2代表获取双十一家电专场几个栏目商品
            List columnIdList=new ArrayList();
            columnIdList.add(116);
            columnIdList.add(117);
            columnIdList.add(118);
            columnIdList.add(119);
            productList = productDao.queryActivityProductList("OLD_FOR_NEW",null,activityMin,activityMax,null,TokenUtil.getPlatformData(),null,columnIdList,null,null);
        }else{
            productList = productDao.queryActivityProductList("OLD_FOR_NEW",columnId,activityMin,activityMax,null,TokenUtil.getPlatformData(),null,null,null,null);
        }
        if (columnId != 15) {//补贴排行不打乱
            if(1==sort) {
                Collections.shuffle(productList);
            }
        }
        List<OldForNewProductDto> oldForNewProductList = productList.stream()
                .map(item -> {
                    OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                    return oldForNewProductDto;
                })
                .collect(Collectors.toList());
        return oldForNewProductList;
    }

    @Override
    public OldForNewReceiveResponse getNotReceiveListV3(Integer pageNum, Integer pageSize) {
        OldForNewReceiveResponse response = new OldForNewReceiveResponse();

        // 获取用户已领补贴的商品
        List<OldForNewProductDto> productResponses = this.getNotReceivedProductsV3(pageNum, pageSize);

        response.setProductList(productResponses);
        response.setUsersFake(this.getFakeUserList());
        return response;
    }

    private List<OldForNewProductDto> getNotReceivedProductsV3(Integer pageNum, Integer pageSize) {
        List<OldForNewProductDto> productResponses = new ArrayList<>();

        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.OLD_FOR_NEW.name())
                .andStatusEqualTo((byte) 1);
        PageHelper.startPage(pageNum, pageSize);
        List<Product> products = productMapper.selectByExample(productExample);
        Collections.shuffle(products);

        if (!CollectionUtils.isEmpty(products)) {
            List<Object> fakeUserList = Optional.ofNullable(redisService.range(RedisConstants.FAKE_USER, 0, -1)).orElse(new ArrayList<>());
            productResponses = products.stream()
                    .filter(product -> !isReceive(product.getId()))
                    .map(item -> {
                        OldForNewProductDto oldForNewProductDto = new OldForNewProductDto(item);
                        Collections.shuffle(fakeUserList);
                        List<String> imgs = fakeUserList.stream()
                                .limit(4)
                                .map(user -> JSONObject.parseObject((String) user, UsersFake.class))
                                .filter(user -> null != user && null != user.getHeadImg())
                                .map(UsersFake::getHeadImg)
                                .collect(Collectors.toList());
                        oldForNewProductDto.setUsersFake(imgs);
                        oldForNewProductDto.setNum(RandomUtil.getSectionNum(700, 1200));
                        return oldForNewProductDto;
                    }).collect(Collectors.toList());

        }
        return productResponses;
    }

    @Override
    public List<OldForNewProductDto> getList(Integer pageNum, Integer pageSize, Integer columnId) {
        PageHelper.startPage(pageNum, pageSize);
        List<OldForNewProductDto> productList = productDao.findOldForNewList(columnId,getSubsidyProductIds(), TokenUtil.getPlatformData());
        for (OldForNewProductDto productDto : productList) {
            productDto.setIsReceiveSubsidy(isReceive(productDto.getId()) ? 1 : 0);
        }
        return productList;
    }

    @Override
    public OldForNewIndexResponse getOldForNewIndex(Integer flag) {
        OldForNewIndexResponse oldForNewIndexResponse=new OldForNewIndexResponse();
        List<OldForNewProductDto> recommendProductList =this.queryOldForNewList(14,1,20,flag);
        recommendProductList = recommendProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        oldForNewIndexResponse.setRecommendProductList(recommendProductList);
        List<OldForNewProductDto> rankProductList =this.queryOldForNewList(15,1,3,flag);
        rankProductList = rankProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        oldForNewIndexResponse.setRankProductList(rankProductList);
        List<OldForNewProductDto> oldForNewProductList = this.queryOldForNewList(0,1,20,flag);
        oldForNewProductList = oldForNewProductList.stream()
                .map(i -> {
                    if(isReceive(i.getId())){
                        i.setIsReceiveSubsidy(1);
                    }else {
                        i.setIsReceiveSubsidy(0);
                    }
                    return i;
                })
                .collect(Collectors.toList());
        Collections.shuffle(oldForNewProductList);
        oldForNewIndexResponse.setProductList(oldForNewProductList);
        return oldForNewIndexResponse;
    }

    @Override
    public VipCenterResponse getVipCenterProduct() {
        VipCenterResponse response = new VipCenterResponse();
        String caseScoreProductKey = sysConfigUtil.getSysConfig("VIP_CENTER_CASH_SCORE_PRODUCTLIST");
        response.setCashScoreProductList(productDao.queryNewYearGoods(this.convertType(caseScoreProductKey))
                .stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList()));
        String getScoreProductKey = sysConfigUtil.getSysConfig("VIP_CENTER_GET_SCORE_PRODUCTLIST");
        response.setGetScoreProductList(productDao.queryNewYearGoods(this.convertType(getScoreProductKey))
                .stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList()));
        String oldForNewProductKey = sysConfigUtil.getSysConfig("VIP_CENTER_OLDFORNEW_PRODUCTLIST");
        List<Product> oldForNewProductList=productDao.queryNewYearGoods(this.convertType(oldForNewProductKey));

        List<ProductResponse> oldForNewProductResponeList=oldForNewProductList.stream()
                .filter(product -> "OLD_FOR_NEW".equals(product.getActivityType()))
                .map(product -> {
                    ProductResponse productResponse = new ProductResponse(product);

                    if (isReceive(product.getId())) {
                        productResponse.setIsReceiveSubsidy(1);
                    } else {
                        productResponse.setIsReceiveSubsidy(0);
                    }

                    return productResponse;
                })
                .collect(Collectors.toList());

        response.setOldForNewProductList(oldForNewProductResponeList);
        return response;
    }

    @Override
    public List<PayAfterUseResponse> getPayAfterUseList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return productDao.findPayAfterUseList();
    }

    /**
     * 获取用户补贴领取信息
     * @return
     */
    @Override
    public OldForNewExtResponse getUserSubsidyInfo(){
        OldForNewExtResponse result=new OldForNewExtResponse();
        // 获取用户补贴领取情况
        RecordSubsidyDataDto recordSubsidyDataDto = this.getUserSubsidyInfo(com.ytjj.qmyx.mall.constants.RedisConstants.RECORD_SUBSIDYKEY);

        BigDecimal totalReceive = recordSubsidyDataDto.getReceived();
        BigDecimal used = recordSubsidyDataDto.getUsed();
        BigDecimal notUsed = totalReceive.compareTo(used) > 0
                ? totalReceive.subtract(used).setScale(0, BigDecimal.ROUND_UP)
                : BigDecimal.ZERO;

        result.setTotalReceive(totalReceive);
        result.setUsed(used);
        result.setNotUsed(notUsed);

        // 获取所有商品补贴价格
        BigDecimal totalProductSubsidy = productDao.queryTotalProductSubsidy(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductSubsidy(Optional.ofNullable(totalProductSubsidy).orElse(BigDecimal.ZERO).setScale(0, BigDecimal.ROUND_HALF_UP));

        // 获取所有商品数量
        Integer totalProductCount = productDao.queryTotalProductCount(ActivityTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        result.setTotalProductCount(Optional.ofNullable(totalProductCount).orElse(0));
        return result;
    }

    @Override
    public List<AppNewLifeHallIndexOldForNewProductDto> getAllList(Integer pageNum, Integer pageSize, Integer columnId) {
        PageHelper.startPage(pageNum, pageSize);
        List<AppNewLifeHallIndexOldForNewProductDto> productDtoList = productDao.findOldForNewListByAll(columnId, null, TokenUtil.getPlatformData());//TokenUtil.getPlatformData()
        if (!CollectionUtils.isEmpty(productDtoList)) {
            productDtoList.stream().forEach(item -> {
                item.setIsReceiveSubsidy(isReceive(item.getId()) ? 1 : 0);
                item.setDiffPrice(item.getPrice().subtract(item.getActivityMax()));
                redisService.sSet(RedisConstants.CUR_POSITION_DATAS, JSON.toJSONString(item));
            });
            redisService.set(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE, "1");
            redisService.expire(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE, 5 * 60);
        }

        CommonPage commonPage = CommonPage.restPage(productDtoList);
        redisService.set(RedisConstants.OLD_FOR_NEW_PAGES, String.valueOf(commonPage.getTotalPage()));

        return productDtoList;
    }

    @Override
    public List<AppNewLifeHallIndexGroupProductDto> getAllListByNew(Integer pageNum, Integer pageSize, Integer columnId) {
        List<AppNewLifeHallIndexGroupProductDto> result = new LinkedList<>();
        PageHelper.startPage(pageNum, pageSize);
        List<AppNewLifeHallIndexOldForNewProductDto> productDtoList = productDao.findOldForNewListByAll(columnId, null, TokenUtil.getPlatformData());//TokenUtil.getPlatformData()
        if (!CollectionUtils.isEmpty(productDtoList)) {
            productDtoList.stream().forEach(item -> {
                AppNewLifeHallIndexGroupProductDto dto = new AppNewLifeHallIndexGroupProductDto();
                dto.setId(item.getId());
                dto.setProductImg(item.getProductImg());
//                dto.setPrice(item.getPrice().subtract(item.getActivityMax()));
                redisService.sSet(RedisConstants.CUR_POSITION_DATAS, JSON.toJSONString(dto));
                result.add(dto);
            });
            redisService.set(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE, "1");
            redisService.expire(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE, 5 * 60);
        }

        CommonPage commonPage = CommonPage.restPage(productDtoList);
        redisService.set(RedisConstants.OLD_FOR_NEW_PAGES, String.valueOf(commonPage.getTotalPage()));

        return result;
    }

    @Override
    public List<ProductShortResponse> getAllCashScoreList(int limit) {
        List<ProductShortResponse> superChangeList = this.getCashScoreByLimit(limit);
        Collections.shuffle(superChangeList);
        List<ProductShortResponse> cash_score_datas = this.screenProductList(superChangeList);
        return cash_score_datas;
    }


    private List<ProductShortResponse> getCashScoreByLimit(int limit) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc limit " + limit);
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductShortResponse> getGroupWorkAll() {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.GROUP_WORK.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public List<Product> getProductByActivityType(String activityType, int limit) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc limit " + limit);
        example.createCriteria()
                .andActivityTypeEqualTo(activityType)
                .andColumnIdNotIn(Arrays.asList(24,53))
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        return products;
    }

    /**
     * 随机
     * @param activityType
     * @param limit
     * @return
     */
    @Override
    public AppIndexTopResponse queryRandomProductByActivityTypeAndLimit(String activityType, int limit, Integer userId) {
        List<Product> products = productMapper.queryRandomProductByActivityTypeAndLimit(activityType, limit);
        List<AppIndexZeroEvaluationProductResponse> results = new LinkedList<>();
        products.stream().forEach(item -> {
            AppIndexZeroEvaluationProductResponse response = new AppIndexZeroEvaluationProductResponse();
            response.setProductImg(item.getProductImg());
            response.setSceneImg(item.getSceneImg());
            results.add(response);
        });
        List<AppIndexYanXuanGuanResponse> yanXuanGuanResponseList = new LinkedList<>();
        List<UsersDto> usersDtoList = usersClient.queryQualityUser(1, 2, "ALL");
        usersDtoList.stream().forEach(item -> {
            AppIndexYanXuanGuanResponse response = new AppIndexYanXuanGuanResponse();
            response.setHeadImg(item.getHeadImg());
            response.setName(item.getNickname());
            yanXuanGuanResponseList.add(response);
        });
        AppIndexTopResponse response = new AppIndexTopResponse();
        response.setZeroProductList(results);
        response.setYanXuanGuanList(yanXuanGuanResponseList);

        if (null != userId) {
            NewExclusiveResponse newExclusiveResponse = newExclusiveDao.selectExclusiveByUserId(userId);
            if (null != newExclusiveResponse) {
                Product product = productMapper.selectByPrimaryKey(newExclusiveResponse.getProductId());

                Date createTime = newExclusiveResponse.getCreateTime();
                long oneDay = 1 * 24 * 60 * 60 * 1000;
                long time = createTime.getTime();
                long dateTime = time + oneDay;
                createTime.setTime(dateTime);

                int max = 3999;
                int min = 2000;
                Random random = new Random();
                int nextInt = random.nextInt(max - min + 1) + min;

                AppNewPreferential appNewPreferential = new AppNewPreferential();
                appNewPreferential
                        .setProductId(product.getId())
                        .setProductImg(product.getProductImg())
                        .setProductName(product.getProductName())
                        .setProductPrice(product.getCurPrice())
                        .setProductType(product.getProductType())
                        .setTimeRemaining(createTime)
                        .setRandomMath(nextInt);
                response.setAppNewPreferential(appNewPreferential);
            }
        }
        return response;
    }

    /**
     * 按照活动类型和栏目id查询商品列表
     * @param pageNum
     * @param pageSize
     * @param activityType
     * @param columnId
     * @return
     */
    @Override
    public List<ActivityProductResponse> getActivityList(Integer pageNum, Integer pageSize, String activityType, Integer columnId) {
//        log.info("domainurl===:{}",TokenUtil.getDomainUrl());
        return getActivityList(pageNum,pageSize,activityType,columnId,TokenUtil.getPlatformData());
    }

    @Override
    public String getColumnName(Integer columnId) {
        ActivityColumn activityColumn = activityColumnMapper.selectByPrimaryKey(columnId);
        if(activityColumn!=null && StringUtils.isNotBlank(activityColumn.getType())){
            return activityColumn.getTitle();
        }
        return null;
    }

    @Override
    public List<ActivityProductResponse> getActivityListByArea(Integer pageNum, Integer pageSize, String activityType, Integer columnId) {
        log.info("地区请求：domainurl===:{}",TokenUtil.getDomainUrl());
        String platform = commonPropertiesConfig.getPlatformByIp();
        return getActivityList(pageNum,pageSize,activityType,columnId,platform);
    }

    /**
     * 按照活动类型和栏目id查询商品列表
     * @param pageNum
     * @param pageSize
     * @param activityType
     * @param columnId
     * @param platformData
     * @return
     */
    @Override
    public List<ActivityProductResponse> getActivityList(Integer pageNum, Integer pageSize, String activityType, Integer columnId, String platformData) {
        StringBuilder key = new StringBuilder("product:activity:list:");
        key = key.append(pageNum).append(pageSize).append(activityType).append(columnId).append(platformData);
        String keyValue = redisService.get(key.toString());
        if (StringUtils.isNotBlank(keyValue)) {
            List<ActivityProductResponse> activityProductList = JSONObject.parseArray(keyValue, ActivityProductResponse.class);
            return activityProductList;
        }

        //排序id
        List<Integer> orderByIdList = null;
        Integer flag = 0 ;
//        if ("app".equals(platformData) && TokenUtil.getDomainUrl().equals("https://vvip.gucmall.cn") && "CASH_SCORE".equals(activityType)) {
//            orderByIdList = new ArrayList<>();
//            Integer index = (pageNum - 1) * pageSize ;
//            List<Integer> collectIdList1 = productDao.queryActivityProductIdList(activityType, columnId, null, null, null, platformData, null, null, index, pageSize);
//            flag = pageNum> 1 ? 2:1;
//            orderByIdList.addAll(collectIdList1);
//        }

        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = new ArrayList<>();
        if(-1==columnId){
            List columnIdList=new ArrayList();
            columnIdList.add(70);
            columnIdList.add(75);
            columnIdList.add(79);
            columnIdList.add(80);
            columnIdList.add(81);
            columnIdList.add(111);
            columnIdList.add(112);
            columnIdList.add(113);
            columnIdList.add(114);
            columnIdList.add(115);
            productList = productDao.queryActivityProductList(activityType,null,null,null,null,platformData,null,columnIdList,orderByIdList,null);
        }else if(-2==columnId){
            List columnIdList=new ArrayList();
            columnIdList.add(8);
            columnIdList.add(10);
            columnIdList.add(49);
            productList = productDao.queryActivityProductList(activityType,null,null,null,null,platformData,null,columnIdList,orderByIdList,null);
        } else if (166 == columnId && ("app".equals(platformData) ||"h5_2".equals(platformData)||"h5_3".equals(platformData) ) && "HOT_SALE".equals(activityType)){
            productList = productDao.queryActivityProductListNew("GUESS_LIKE",platformData,orderByIdList,flag);
        }else{
            productList = productDao.queryActivityProductList(activityType,columnId,null,null,null,platformData,null,null,orderByIdList,flag);
        }
        if (CollectionUtils.isEmpty(productList)){
            return new ArrayList<>();
        }
        //获取商品所有规格属性
        List<ProductSpecResponse> productsSpecList = productService.getProductsSpecList(productList);
        List<Product> products = new ArrayList<>();
        //供应链商品id
        List<Integer> supplyProductIds = productList.stream().filter(item -> null != item.getSupplyProductId()).map(Product::getSupplyProductId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(supplyProductIds)){
            ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
            productReceiveRequest.setProductIds(supplyProductIds);
            String json = com.alibaba.fastjson.JSON.toJSONString(productReceiveRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
            products = JSONObject.parseArray(result, Product.class);
        }
        //获取商品标签
        List<Integer> productIds = productList.stream().filter(item -> null != item.getId()).map(Product::getId).collect(Collectors.toList());
        List<ActivityProductLabel> productLabels = productDao.findProductLabels(productIds);
        Map<Integer, List<Product>> collect = products.stream().collect(Collectors.groupingBy(Product::getId));
        List<ActivityProductResponse> activityProductList = productList.stream()
                .map(item -> {
                    if(!CollectionUtils.isEmpty(collect)){
                        List<Product> products1 = collect.get(item.getSupplyProductId());
                        Product product = products1.get(0);
                        item.setBrand(product.getBrand());
                        item.setBrandId(product.getBrandId());
                    }
                    item.getSupplyProductId();
                    ActivityProductResponse activityProductResponse = new ActivityProductResponse(item);
                    if (!CollectionUtils.isEmpty(productsSpecList)) {
                        Optional<ProductSpecResponse> priceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getPrice));
                        BigDecimal price = null;
                        if (priceOptional.isPresent()) {
                            price = priceOptional.get().getPrice();
                        }
                        Optional<ProductSpecResponse> curPriceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getCurPrice));
                        BigDecimal curPrice = null;
                        if (curPriceOptional.isPresent()) {
                            curPrice = curPriceOptional.get().getCurPrice();
                        }
                        Optional<ProductSpecResponse> originalPriceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getOriginalPrice));
                        BigDecimal originalPrice = null;
                        if (originalPriceOptional.isPresent()) {
                            originalPrice = originalPriceOptional.get().getOriginalPrice();
                        }
                        activityProductResponse.setPrice(Optional.ofNullable(price).orElse(activityProductResponse.getPrice()));
                        activityProductResponse.setCurPrice(Optional.ofNullable(curPrice).orElse(activityProductResponse.getCurPrice()));
                        activityProductResponse.setOriginalPrice(Optional.ofNullable(originalPrice).orElse(activityProductResponse.getOriginalPrice()));
                    }
                    if (!CollectionUtils.isEmpty(productLabels)) {
                        List<ActivityProductLabel> labels = productLabels.stream().filter(item2 -> item2.getProductId().equals(item.getId())).collect(Collectors.toList());
                        activityProductResponse.setLabels(labels);
                    }
                    return activityProductResponse;
                })
                .collect(Collectors.toList());
        activityProductList=activityProductList.stream().map(item -> {
            try {
                //有设置秒杀占比
                item.setActivityMin(Optional.ofNullable(item.getActivityMin()).orElse(BigDecimal.ZERO));
                if(item.getActivityMin().intValue()>0&&item.getActivityMin().intValue()<100){
                    item.setStockProgress(item.getActivityMin().intValue());
                    item.setStockProgressStr(item.getActivityMin().intValue() + "%");
                }else {
                    BigDecimal baseStock = new BigDecimal(Optional.ofNullable(item.getStock() % 17).orElse(0))
                            .multiply(new BigDecimal(100))
                            .divide(new BigDecimal(5000), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal stockProgress = new BigDecimal(1)
                            .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    if (stockProgress.intValue() >= 100 || stockProgress.intValue() <= 0) {
                        item.setStockProgress(60);
                        item.setStockProgressStr("60%");
                    } else {
                        item.setStockProgress(stockProgress.intValue());
                        item.setStockProgressStr(stockProgress.intValue() + "%");
                    }
                }
            } catch (ApiException e) {
                item.setStockProgress(80);
                item.setStockProgressStr("80%");
            }
            return item;
        }).collect(Collectors.toList());
        redisService.set(key.toString(), com.alibaba.fastjson.JSON.toJSONString(activityProductList));
        redisService.expire(key.toString(), 2 * 60);
        return activityProductList;
    }

    public static void main(String[] args) {
        int pageNum = 1;
        int pageSize = 10;
        int startIndex = pageNum -1 * pageSize;


    }

    /**
     * 获取首页专题商品
     * (专题活动入口展示的商品)
     */
    @Override
    public CommonResult getHomeSubjectProduct() {
        List<HomeSubjectResponse> homeSubjectResponses = new ArrayList<>();
        String sysConfig = "sys:config";
        //查所有专题
        SubjectsExample subjectsExample = new SubjectsExample();
        subjectsExample.createCriteria().andIsDeletedEqualTo(0);
        subjectsExample.setOrderByClause("id asc limit 4");
        List<Subjects> subjects = subjectsMapper.selectByExample(subjectsExample);
        subjects.stream().forEach(item ->{
            HomeSubjectResponse homeSubjectResponse = new HomeSubjectResponse();
            List<ProductSubjectPlateResponse> responses = new ArrayList<>();
            String imgRedis ="";
            String globalImgRedis = "";
            String discountImgRedis = "";
            if (item.getId() == 1){
                imgRedis = redisService.getMapString(sysConfig, "APP_LIVE_9.9_IMG");
            }else if (item.getId() == 2){
                imgRedis = redisService.getMapString(sysConfig, "APP_LIVE_BRAND_IMG");
                discountImgRedis = redisService.getMapString(sysConfig, "APP_LIVE_BRAND_DISCOUNT_IMG");
            }else if (item.getId() == 3){
                imgRedis = redisService.getMapString(sysConfig, "APP_LIVE_GLOBAL_IMG");
                globalImgRedis = redisService.getMapString(sysConfig, "APP_LIVE_GLOBAL_ENSIGN_IMG");
            }else if (item.getId() == 4){
                imgRedis = redisService.getMapString(sysConfig, "APP_LIVE_AGRICULTURAL_IMG");
            }
            String[] imgs = imgRedis.split(",");
            String[] globalImgs = globalImgRedis.split(",");
            for (int i = 0; i < imgs.length; i++) {
                ProductSubjectPlateResponse productSubjectPlateResponse = new ProductSubjectPlateResponse();
                productSubjectPlateResponse.setProductImg(imgs[i]);
                if (item.getId() == 1){
                    productSubjectPlateResponse.setProductPrice("9.9");
                }else if (item.getId() == 2){
                    productSubjectPlateResponse.setLabelUrl(discountImgRedis);
                }else if (item.getId() == 3){
                    productSubjectPlateResponse.setLabelUrl(globalImgs[i]);
                }
                responses.add(productSubjectPlateResponse);
            }

            homeSubjectResponse.setSubjectId(item.getId());
            homeSubjectResponse.setTitle(item.getTitle());
            homeSubjectResponse.setProductSubjectPlates(responses);
            homeSubjectResponses.add(homeSubjectResponse);
        });
        //全民补贴
        BigDecimal activityMin=new BigDecimal(500);
        BigDecimal activityMax=new BigDecimal(2000);
        List<Product> old_for_new = productDao.queryActivityProductListRand("OLD_FOR_NEW", 37, activityMin, activityMax, null, TokenUtil.getPlatformData(), null, null);
        HomeSubjectResponse homeSubjectResponse = new HomeSubjectResponse();
        List<ProductSubjectPlateResponse> quanming = new ArrayList<>();
        old_for_new.stream().forEach(item ->{
            ProductSubjectPlateResponse productSubjectPlateResponse = new ProductSubjectPlateResponse();
            productSubjectPlateResponse.setProductId(item.getId());
            productSubjectPlateResponse.setProductImg(item.getProductImg());
            productSubjectPlateResponse.setProductPrice(item.getPrice().setScale(0,BigDecimal.ROUND_UP).toString());
            productSubjectPlateResponse.setActivityMax(item.getActivityMax().setScale(0,BigDecimal.ROUND_UP));
            quanming.add(productSubjectPlateResponse);
        });
        homeSubjectResponse.setSubjectId(66);
        homeSubjectResponse.setTitle("全民补贴");
        homeSubjectResponse.setProductSubjectPlates(quanming);
        homeSubjectResponses.add(homeSubjectResponse);
        //大额神券
        List<ProductSubjectPlateResponse> dae = new ArrayList<>();
        HomeSubjectResponse homeSubjectResponseTwo = new HomeSubjectResponse();
        String blockRedis = redisService.getMapString(sysConfig, "APP_LIVE_BLOCK_IMG");//大额神券图片
        String couponImgRedis = redisService.getMapString(sysConfig, "APP_LIVE_BLOCK_COUPON_IMG");//大额神券优惠卷图片
        String[] blockImgs = blockRedis.split(",");
        String[] couponImgs = couponImgRedis.split(",");
        for (int i = 0; i < blockImgs.length; i++) {
            ProductSubjectPlateResponse productSubjectPlateResponse = new ProductSubjectPlateResponse();
            productSubjectPlateResponse.setProductImg(blockImgs[i]);
            productSubjectPlateResponse.setLabelUrl(couponImgs[i]);
            dae.add(productSubjectPlateResponse);
        }
//        List<Product> products = productDao.queryActivityProductListRand(ActivityTypeEnums.CASH_COUPON.name(), 0, null, null, null, TokenUtil.getPlatformData(), null, null);
//        HomeSubjectResponse homeSubjectResponseTwo = new HomeSubjectResponse();
//        products.stream().forEach(item ->{
//            ProductSubjectPlateResponse productSubjectPlateResponse = new ProductSubjectPlateResponse();
//            productSubjectPlateResponse.setProductId(item.getId());
//            productSubjectPlateResponse.setProductImg(item.getProductImg());
//            productSubjectPlateResponse.setActivityMax(item.getActivityMax());
//            dae.add(productSubjectPlateResponse);
//        });
        homeSubjectResponseTwo.setSubjectId(88);
        homeSubjectResponseTwo.setTitle("大额神券");
        homeSubjectResponseTwo.setProductSubjectPlates(dae);
        homeSubjectResponses.add(homeSubjectResponseTwo);
        return CommonResult.success(homeSubjectResponses);
    }
    @Override
    public BigDecimal queryH5TotalUsedScore() {
        return ordersDao.queryH5TotalUsedScore(TokenUtil.getToken());
    }

    @Override
    public int newUserDeliveryAddress(NewExclusiveResponse newExclusiveResponse) {
//        if (null != redisService.get(RedisConstants.New_Preferential_KEY + usersAddress.getUserId())) {
//            throw new ApiException("您已领取过该商品了");
//        }
        NewExclusiveResponse newExclusive = newExclusiveDao.selectExclusiveByUserId(newExclusiveResponse.getUserId());
        if (null != newExclusive) {
            throw new ApiException("您已领取过该商品了");
        }

        UsersInfo usersInfo = usersInfoMapper.selectByPrimaryKey(newExclusiveResponse.getUserId());
        if (null != usersInfo.getIsQuality() && usersInfo.getIsQuality().equals(1)) {
            throw new ApiException("新用户才能参与哦");
        }

//        redisService.set(RedisConstants.New_Preferential_KEY + usersAddress.getUserId(), String.valueOf(usersAddress.getProductId()));
//        redisService.expire(RedisConstants.New_Preferential_KEY + usersAddress.getUserId(), 1 * 24 * 60 * 60);
//        usersAddress.setStatus((byte) 0)
//                .setCreateTime(new Date())
//                .setUpdateTime(new Date());
//        return usersAddressMapper.insert(usersAddress);
        boolean exclusive = newExclusiveDao.insertNewExclusive(newExclusiveResponse);
        int num = exclusive == true ? 1 : 0 ;
        return num;
    }

    @Override
    public ScorePageResponse getScoreListByTypeCopy(UsersResponse user) {
        ScorePageResponse response = new ScorePageResponse();

        String key = com.ytjj.qmyx.mall.constants.RedisConstants.ACTIVITY_PRODUCT + ActivityTypeEnums.CASH_SCORE.name() + TokenUtil.getDataType() + "_APPCASH";
        String s = redisService.get(key);
        redisService.delete(key);
        if (StringUtils.isNotEmpty(s)) {
            response = JSONObject.parseObject(s, ScorePageResponse.class);
        } else {
            response.setCashScoreColumn(this.getCashScoreListCopy());
            // 品牌列表
            BrandExample brandExample = new BrandExample();
            brandExample.setOrderByClause("sort desc");
            brandExample.createCriteria().andStatusEqualTo(1);
            List<Brand> brandList = brandMapper.selectByExample(brandExample);
            response.setBrandList(brandList);
            // 假用户
            List<Object> fakeUserList = redisService.range(RedisConstants.FAKE_USER, 0, -1);
            Collections.shuffle(fakeUserList);
            List<UsersFake> usersFake = fakeUserList.stream()
                    .map(userItem -> JSONObject.parseObject((String) userItem, UsersFake.class))
                    .limit(20)
                    .collect(Collectors.toList());
            response.setUsersFakes(usersFake);
            // 假用户数量
            response.setUsersNum(RandomUtil.getSectionNum(700, 1000));

            redisService.set(key, JSONObject.toJSONString(response));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }

        if (user == null) {
            response.setScore(Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE)));
            response.setIsSign(0);// 前端要在app中没有用户登录的时候,签到也不要返回null,而要返回0
        } else {
            UsersDto usersDto = usersClient.getUsersInfo(user.getId());
            response.setScore(usersDto.getScore());
            response.setIsSign(usersClient.isSign(user.getId()));
        }
        response.setDefaultScore(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_SCORE));
        return response;
    }

    @Override
    public List<ActivityProductResponse> getActivityListByColumnIds(Integer pageNum, Integer pageSize, String activityType, String columnIds) {
        return getActivityListByColumnIds(pageNum,pageSize,activityType,columnIds,TokenUtil.getPlatformData());
    }

    @Override
    public List<ActivityProductResponse> getActivityListByColumnIds(Integer pageNum, Integer pageSize, String activityType, String columnIds, String platformData) {

        List columnIdList = Arrays.asList(columnIds.split(","));
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.queryActivityProductList(activityType,null,null,null,null,platformData,null,columnIdList,null,null);

        List<ActivityProductResponse> activityProductList = productList.stream()
                .map(item -> {
                    ActivityProductResponse activityProductResponse = new ActivityProductResponse(item);
                    return activityProductResponse;
                })
                .collect(Collectors.toList());
        activityProductList=activityProductList.stream().map(item -> {
            try {
                //有设置秒杀占比
                if(item.getActivityMin().intValue()>0&&item.getActivityMin().intValue()<100){
                    item.setStockProgress(item.getActivityMin().intValue());
                    item.setStockProgressStr(item.getActivityMin().intValue() + "%");
                }else {
                    BigDecimal baseStock = new BigDecimal(Optional.ofNullable(item.getStock() % 17).orElse(0))
                            .multiply(new BigDecimal(100))
                            .divide(new BigDecimal(5000), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal stockProgress = new BigDecimal(1)
                            .subtract(baseStock).setScale(2, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    if (stockProgress.intValue() >= 100 || stockProgress.intValue() <= 0) {
                        item.setStockProgress(60);
                        item.setStockProgressStr("60%");
                    } else {
                        item.setStockProgress(stockProgress.intValue());
                        item.setStockProgressStr(stockProgress.intValue() + "%");
                    }
                }
            } catch (ApiException e) {
                item.setStockProgress(80);
                item.setStockProgressStr("80%");
            }
            return item;
        }).collect(Collectors.toList());
        return activityProductList;
    }

    private Map<String, List<ProductShortResponse>> getCashScoreListCopy() {
        Map<String, List<ProductShortResponse>> cashScoreColumn = new HashMap<>();

        // 查询全部积分商品
        List<ProductShortResponse> superChangeList = this.getCashScoreAllCopy();
        Collections.shuffle(superChangeList);
        cashScoreColumn.put("SUPER_CHANGE", this.screenProductList(superChangeList));
        // 排行榜的数据
        List<ProductShortResponse> changeSeniorityList = this.getCashScoresCopy(9, CHANGE_RANKING);
        cashScoreColumn.put("CHANGE_SENIORITY", this.screenProductList(changeSeniorityList));
        // 猜你喜欢
        List<ProductShortResponse> getLikeList = this.getCashScoresCopy(6, GUESSYOU_LIKE);
        cashScoreColumn.put("GET_LIKE", this.screenProductList(getLikeList));
        // 品质好物
        List<ProductShortResponse> veryScoreList = this.getCashScoresCopy(6, CHOICENESS_GOODTHING);
        cashScoreColumn.put("VERY_SCORE", this.screenProductList(veryScoreList));
        // 返积分商品
        List<ProductShortResponse> getScoreList = screenProductList(this.getReturnCashList(ActivityTypeEnums.GET_SCORE.name()));
        cashScoreColumn.put("GET_SCORE", getScoreList);

        List<ProductShortResponse> cashScoreZero = productDao.findCashScoreZero(TokenUtil.getPlatformData());
        cashScoreColumn.put("CASH_SCORE_ZERO", cashScoreZero);

        return cashScoreColumn;
    }

    private List<ProductShortResponse> getCashScoreAllCopy() {
        ProductExample example = new ProductExample();
        example.setOrderByClause("sort desc");
        example.createCriteria()
                .andActivityTypeEqualTo(ActivityTypeEnums.CASH_SCORE.name())
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusEqualTo((byte) 1);
        List<Product> products = productMapper.selectByExample(example);
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    private List<ProductShortResponse> getCashScoresCopy(Integer num, String activityColumId) {
        List<String> asList = Arrays.asList(TokenUtil.getPlatformData(), "all");
        Product product = new Product();
        product.setActivityColumnIds(activityColumId);
        product.setActivityType(ActivityTypeEnums.CASH_SCORE.name());
        List<Product> products = productDao.findProductByColumIds(product,asList);
        Collections.shuffle(products);
        if (num != null) {
            products = products.stream().limit(num).collect(Collectors.toList());
        }
        return products.stream()
                .map(ProductShortResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public CommonResult getColumn(String activityType, Integer isShow) {
        if (StringUtils.isBlank(activityType)){
            return CommonResult.success(new ArrayList<>());
        }
        List<ActivityColumn> list = new ArrayList<>();
//        List<ActivityColumn> list = activityColumnMapper.selectByActivityType(activityType,isShow,TokenUtil.getPlatformData());
        String platformData = TokenUtil.getPlatformData();
        if (StringUtils.isNotBlank(activityType) && "HOT_SALE".equals(activityType) && ("app".equals(platformData) || "h5_2".equals(platformData) || "h5_3".equals(platformData))) {
            ActivityColumn activityColumn = activityColumnMapper.selectByPrimaryKey(166);
            list.add(activityColumn);
        } else {
            list = activityColumnMapper.selectByActivityType(activityType,isShow, null);
        }

        if (!CollectionUtils.isEmpty(list)){
            list.stream().forEach(item ->{
                String title = item.getTitle();
                if (title.contains("-")){
                    item.setTitle(title.substring(0, title.indexOf("-")));
                }
            });
        }
        return CommonResult.success(list);
    }

    @Override
    public List<ActivityProductResponse> queryActivityRankList(Integer specialId, List<Integer> ids, Integer pageNum, Integer pageSize) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList();
        }
        StringBuilder key = new StringBuilder("product:special:rankList:");
        key = key.append(pageNum).append(pageSize).append(specialId);
        String keyValue = redisService.get(key.toString());
        if (StringUtils.isNotBlank(keyValue)) {
            List<ActivityProductResponse> activityProductList = JSONObject.parseArray(keyValue, ActivityProductResponse.class);
            return activityProductList;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.queryActivityRankList(ids);
        List<ActivityProductResponse> activityProductList = productList.stream()
                .map(item -> {
                    ActivityProductResponse activityProductResponse = new ActivityProductResponse(item);
                    return activityProductResponse;
                })
                .collect(Collectors.toList());
        redisService.set(key.toString(), JSONObject.toJSONString(activityProductList));
        redisService.expire(key.toString(), 2 * 60);
        return activityProductList;
    }

    @Override
    public List<ActivityProductResponse> recommendProduct(Integer productId, Integer pageNum, Integer pageSize) {
        Product product = productMapper.selectByPrimaryKey(productId);
        Assert.notNull(product,"商品不存在");
        Integer bottomCategoryId = product.getBottomCategoryId();
        Integer categoryId = product.getCategoryId();
        Integer topCategoryId = product.getTopCategoryId();

        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productDao.getRecommendProduct(bottomCategoryId,null,null,TokenUtil.getPlatformData());
        if (productList==null || productList.size()<pageSize){
            PageHelper.startPage(pageNum, pageSize-productList.size());
            List<Product> categoryList = productDao.getRecommendProduct(null,categoryId,null,TokenUtil.getPlatformData());
            if (productList==null && categoryList!=null ){
                productList = categoryList;
            }
            if (productList!=null && productList.size()<pageSize && categoryList!=null){
                productList.addAll(categoryList);
            }
            if (productList!=null && productList.size()<pageSize){
                PageHelper.startPage(pageNum, pageSize-productList.size());
                List<Product> topCategoryList = productDao.getRecommendProduct(null,null,topCategoryId,TokenUtil.getPlatformData());
                productList.addAll(topCategoryList);
            }
        }
        if (CollectionUtils.isEmpty(productList)){
            return new ArrayList<>();
        }
        //获取商品所有规格属性
        List<ProductSpecResponse> productsSpecList = productService.getProductsSpecList(productList);
        List<ActivityProductResponse> activityProductList = productList.stream()
                .map(item -> {
                    ActivityProductResponse activityProductResponse = new ActivityProductResponse(item);
                    if (!CollectionUtils.isEmpty(productsSpecList)) {
                        Optional<ProductSpecResponse> priceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getPrice));
                        BigDecimal price = null;
                        if (priceOptional.isPresent()) {
                            price = priceOptional.get().getPrice();
                        }
                        Optional<ProductSpecResponse> curPriceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getCurPrice));
                        BigDecimal curPrice = null;
                        if (curPriceOptional.isPresent()) {
                            curPrice = curPriceOptional.get().getCurPrice();
                        }
                        Optional<ProductSpecResponse> originalPriceOptional = productsSpecList.stream().filter(item2 -> item2.getProductId().equals(item.getId()) &&
                                item2.getStock() != null && item2.getStock() > 0).min(Comparator.comparing(ProductSpecResponse::getOriginalPrice));
                        BigDecimal originalPrice = null;
                        if (originalPriceOptional.isPresent()) {
                            originalPrice = originalPriceOptional.get().getOriginalPrice();
                        }
                        activityProductResponse.setPrice(Optional.ofNullable(price).orElse(activityProductResponse.getPrice()));
                        activityProductResponse.setCurPrice(Optional.ofNullable(curPrice).orElse(activityProductResponse.getCurPrice()));
                        activityProductResponse.setOriginalPrice(Optional.ofNullable(originalPrice).orElse(activityProductResponse.getOriginalPrice()));
                    }
                    return activityProductResponse;
                })
                .collect(Collectors.toList());
        return activityProductList;
    }
}
